Yuce's Blog

Cognitive dissonance is yoga for the brain.*

Getting the Current Module in Python

2009-10-15

Say, you want to insert a function, class or any other object into the current module dy­nam­i­cal­ly. How can you do that? Of course, you start with getting the module name:

myName = globals()['__name__']

Then, get the module itself:

import sys
me = sys.modules[myName]

OK, you got the module, now insert something in it:

setattr(me, 'hello', lambda x: 'Hello %s'%x)

We can call hello in our module from now on:

print hello('World')

python, tips

comments powered by Disqus