Replace a module variable with a function call

Tim Hochberg tim.hochberg at ieee.org
Mon Feb 6 14:26:46 EST 2006


gabriel.becedillas at gmail.com wrote:
> I have a module that defines a variable with a constant value and now I
> need to make that value dynamic, without affecting module clients. In
> other words, I need to call a function witout using parenthesis.
> Example:
> 
> mymod.py----------------------
> 
> def value():
>     return "hi"
> 
> client.py--------------------------
> import mymod
> 
> print mymod.value
> 
> Is there a way to do this ?


It can be done, but you're not really supposed to be doing this, so it's 
moderately horrible to do so. If you can manage, I'd avoid doing this, 
but if you have to, the strategy is to (1) move the contents of your 
module into a class, (2) use properties to convert what is now a method 
call into an attribute access and (3) replace the module in sys.modules 
with an instance of this class. This occasionally get you into trouble, 
for instance reload no longer works, but it has mostly worked in my 
limited experience.

Since I'm sure that's pretty opaque, here's an example:

# file noparens.py
import sys

class Module(object):

     def get_value(self):
         return "hi"
     value = property(get_value)

sys.modules[__name__] = Module()

# interpreter session
 >>> import noparens
 >>> noparens.value
'hi'

regards,

-tim




More information about the Python-list mailing list