Python using function like variable -
i've got python module has several variables hard-coded values used throughout project. i'd bind variables somehow function redirect config file. possible?
# hardcoded_values.py foo = 'abc' bar = 1234  # usage somewhere else in module hardcoded_values import * print foo print bar   what want change hardcoded_values.py, print foo transparently calls function.
# hardcoded_values.py import config foo = somewrapper(config.get_value, 'foo') # or whatever can think of call config.get_value('foo') ...   config.get_value function called parameter 'foo' when using variable foo (as in print foo).
i'm pretty sure can't want if import from hardcoded_values import *. 
what want set foo function, , apply property decorator (or equivalent) can call foo foo rather foo(). cannot apply property decorator modules reasons detailed here: why property decorator defined classes?
now, if import hardcoded_values think there way want hardcoded_values.foo. have pretty feeling describe bad idea should never used, think interesting.
bad idea???
so wanted replace constant os.ex_usage on system 64 function, , call os.ex_usage rather os.ex_usage(). need able use property decorator, need type other module.
so can done create new type on fly , dump in __dict__ of module type factory function takes module argument:
def module_class_factory(module):     moduleclass = type('moduleclass' + module.__name__,                         (object,), module.__dict__)     return moduleclass   now import os:
>>> import os >>> os.ex_usage 64 >>> os.getcwd() '/users/eric'   now make class osclass, , bind name os instance of class:
>>> osclass = module_class_factory(os) >>> os = osclass() >>> os.ex_usage 64 >>> os.getcwd() '/users/eric'   everything still seems work. define function replace os.ex_usage, noting need take dummy self argument:
>>> def foo(self): ...     return 42 ...    ...and bind class attribute osclass.ex_usage function:
>>> osclass.ex_usage = foo >>> os.ex_usage() 42   it works when called os object! apply property decorator:
>>> osclass.ex_usage = property(osclass.ex_usage) >>> os.ex_usage 42   now constant defined in module has been transparently replaced function call.
Comments
Post a Comment