With python properties, I can make it such that
x.y
calls a function rather than just returning a value.
Is there a way to do this with modules?
I have a case where I want m.y to call a function rather than just returning the value stored there.
C
With python properties, I can make it such that
x.y
calls a function rather than just returning a value.
Is there a way to do this with modules?
I have a case where I want m.y to call a function rather than just returning the value stored there.
C
Only instances of new-style classes can have properties. You can make Python believe such an instance is a module by stashing it in sys.modules[thename] = theinstance. So, for example, your m.py module file could be:
import sys
class _M(object):
def __init__(self):
self.c = 0
def afunction(self):
self.c += 1
return self.c
y = property(afunction)
sys.modules[__name__] = _M()
Edited: removed an implicit dependency on globals (had nothing to do with the point of the example but did confuse things by making the original code fail!).
I would do this in order to properly inherit all the attributes of a module, and be correctly identified by isinstance()
import types
class MyModule(types.ModuleType):
@property
def y(self):
return 5
>>> a=MyModule("test")
>>> a
<module 'test' (built-in)>
>>> a.y
5
And then you can insert this into sys.modules