0

I've written a very simple select function for SQLite, but I'm confused at how to pass a member function... e.g.: .fetchone(), .fetchmany().

def select(cursor, select="*", table="reuters", fetch=".fetchone()", tologfile=False, logfile=""):
    if tologfile:
        logfile = open(logfile, 'w')
        logfile.write(str(cursor.execute("select * from ?;".replace('?',table).replace("select * ", "select "+select)).fetchone()))
        logfile.close()
    else: return str(cursor.execute("select * from ?;".replace('?',table).replace("select * ", "select "+select)).fetchone())

How do I pass this member function as an arg?

user1438003
  • 6,603
  • 8
  • 30
  • 36

4 Answers4

3

You can simply pass self.fetchone to pass that function.

If you want it as a default value simply use None in the function definition and add

if whatever is None:
    whatever = self.fetchone

in the function itself.

If you want to call the method on another object but self keep passing it as a string and use this code (based on your else code since that one's shorter):

result = self.execute("select * from ?;".replace('?',table).replace("select * ", ("select "+attr)))
return str(getattr(result, whatever)())
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
2

You could use getattr :

>>> class A:
...     def b(self):
...             print 'c'
... 
>>> a = A()
>>> getattr(a,'b')
<bound method A.b of <__main__.A instance at 0x7f2a24a85170>>
>>> getattr(a,'b')()
c
Zashas
  • 736
  • 4
  • 11
0

A lambda could achieve this

class A:
  def test(self):
    print "hello world"

a = A()
func = (lambda: a.test())
func()

prints "hello world"

This technique can also be extended to deal with passing and transforming arguments

class B:
  def test(self, x):
    print x

b = B()
func = (lambda a, b : b.test(b))
func("garbage", "foo")

prints "foo"

cjh
  • 1,113
  • 1
  • 9
  • 21
0

Okay, got it to work:

import sqlite3

def select(self, attr="*", table="reuters", fetch=None, num=None, tologfile=False, logfile=""):
    if fetch is None:
        fetch=self.fetchone
    output=self.execute("select * from ?;".replace('?',table).replace("select * ", ("select "+attr+' ')))

    output=fetch(num) if num else fetch()

    if tologfile:
        logfile = open(logfile, 'w')
        logfile.write(str(output))
        logfile.close()
    else: return output

if __name__ == '__main__':    
    connection = sqlite3.connect('winkwinknudgenudgesaynomore.db')
    cursor = connection.cursor()
    cursor.execute("drop table reuters;")
    cursor.execute("create table reuters (foo text, bar text);")
    connection.commit()
    print select(cursor)
    print select(cursor, 'bar')
    print select(cursor, 'bar', fetch=cursor.fetchmany, num=5)
    cursor.close()
user1438003
  • 6,603
  • 8
  • 30
  • 36