Callable modules?

Bengt Richter bokr at oz.net
Wed Jul 24 21:36:07 EDT 2002


On 24 Jul 2002 17:01:52 -0700, Paul Rubin <phr-n2002b at NOSPAMnightsong.com> wrote:

>bokr at oz.net (Bengt Richter) writes:
>> >> If the main purpose of the module is to provide one function, I think
>> >> it's cleaner to be able to import the module and call the function
>> >> without special tricks.
>> Or just use your own trick, e.g., given
>> 
>> ----< PR.py >------
>> #PR.py for Paul Rubin
>> def PR(): return 'Hi Paul'
>> -------------------
>> 
>> Define one-line trick:
>>  >>> def PRimport(name, locs=locals()): locs[name] = getattr(__import__(name),name)
>>  ...
>> 
>> And use it thus
>>  >>> PRimport('PR')
>>  >>> PR
>>  <function PR at 0x007D8FD0>
>>  >>> PR()
>>  'Hi Paul'
>
>But that's another special trick, more hair to remember.  Why not just
>do the obvious thing and make modules work the same way as other objects?

Ok, if you have a single function, add two lines of fixed boilerplate
to your module if you want it to work that way:

----------------------------
#PR2.py for Paul Rubin
def PR2(): return 'Hi Paul'

import sys
sys.modules[__name__] = eval(__name__)
----------------------------

 >>> import PR2
 >>> PR2()
 'Hi Paul'
 >>> dir()
 ['PR2', '__builtins__', '__doc__', '__name__']

Note that you could have substituted foo for eval(__name__)
if you wanted to bind PR2 to function foo in the module.

Regards,
Bengt Richter



More information about the Python-list mailing list