A simple object wrapper that allows you to define pre-defined parameters for functions (global for all functions associated with the object).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | """
SimpleWrapper 1.0
Author: Jonas Galvez <jonasgalvez@gmail.com>
"""
class SimpleWrapper:
class MethodCall:
def __init__(self, function, *params):
self.function = function
self.default_params = params
def __call__(self, *params):
return self.function(*(self.default_params + params))
def __init__(self, ns, *params):
self.params = params
self.ns = ns
def __getattr__(self, attr):
return SimpleWrapper.MethodCall(self.ns[attr], *self.params);
if __name__ == '__main__':
# Simple esage example
# ---------------------------------------------------
def foo(a, b, c):
print a, b, c
def bar(a, b, c):
print a, b, c
o = SimpleWrapper(globals(), 1)
o.foo(2, 3)
o.bar(4, 5)
# ---------------------------------------------------
# And here's the scenario that led me into coding it:
# ---------------------------------------------------
def main(u, p, *db_data):
db = connect_db('localhost', *db_data)
db.create_table()
db.populate_table(feeds)
# ...
def connect_db(*k):
import MySQLdb
conn = MySQLdb.connect(*k)
return SimpleWrapper(globals(), conn.cursor())
def create_table(cursor):
pass # ...
def populate_table(cursor, feeds):
pass # ...
# ---------------------------------------------------
|
I use Python for a lot of quick hacks, and to keep code reasonably organized, I always put things into small functions (I find it to be overkill to create entire classes for these kinds of quick hacks). As a result, my scripts often end up looking rather ugly, perhaps too "procedural" for my tastes.
For example, having to repeatedly pass a database cursor reference to multiple functions. I've always thought it would be nice to have some sort of generic wrapper that would allow me call global functions as if they were part of an object.
I mulled that over for a long time, until I finally did it. And here's the result. It's a rather messy implementation, and maybe someone will be able to show me a better alternative, but it worked just fine for me. Take a look at the second usage example and you'll see what my thoughts were.
isn't this what classes are for?
see PEP 309. Check out PEP 309: http://www.python.org/peps/pep-0309.html