Reputation: 7952
How would you add all functions from some module as methods of a specified object?
If you have module modulename
you can import all it's methods with
from modulename import *
I want to add them as methods of some obj
instead cause they all accept that object as the first paramater and I find x.y(z)
to be more fun than y(x,z)
because of habit.
Upvotes: 0
Views: 29
Reputation: 1228
Try this:
from inspect import getmembers, isfunction
import modulename
class Obj(object):
...
obj_ = Obj()
for name, func in getmembers(modulename, isfunction):
setattr(obj_, name, func)
print(obj_.__dict__)
Upvotes: 1
Reputation: 7952
def add_methods(driver):
for name, obj in inspect.getmembers(sys.modules[__name__]):
if inspect.isfunction(obj) and name != 'add_methods':
setattr(driver, name, obj.__get__(driver))
Upvotes: 0