Suppose I have a file with a bunch methods as bunch_methods.py:
def one(x):
return int(x)
def two(y)
return str(y)
Is there a way to take th
No idea why you want to do this, but a simple approach could be:
def to_class(module):
class TheClass(object): pass
for attr in dir(module):
val = getattr(module, attr)
if callable(val):
setattr(TheClass, attr, staticmethod(val))
return TheClass
Usage:
>>> import math
>>> Math = to_class(math)
>>> m = Math()
>>> m.sin(5)
-0.9589242746631385
>>> math.sin(5)
-0.9589242746631385
>>> Math.sin(5)
-0.9589242746631385
If the module has also some variables, you could enhance it to add non-callable objects to the class too:
def to_class(module):
class TheClass(object): pass
for attr in dir(module):
val = getattr(module, attr)
if callable(val):
setattr(TheClass, attr, staticmethod(val))
else:
setattr(TheClass, attr, val)
return TheClass
However doing more than this becomes really hard and ugly and you must have a really good reason for doing this, otherwise it's wasted effort.