Creating "virtual" module-namespace

Bengt Richter bokr at oz.net
Thu Dec 12 04:11:36 EST 2002


On Wed, 11 Dec 2002 23:17:43 +0100, Simon <simon.12.ghum at spamgourmet.com> wrote:

>Imagine... there is a:
>
>a= "class nasenbaer:\n  def singt():\n    print "tralala"\n\n"
>
>(the content of a is:
>class nasenbaer:
>    	def singt():
>    	    	print "tralala"
>
>
>)
>
>now I want to exec a in a "special" way so that later I can call
>
>exec a in ???????
>
>grail=somthing.nasenbaer()
>grail.singt()
>
>My try was 
>
>b=globals()
>
>exec a in b
>grail=b.nasenbaer()
>
>but it failed...
>
>what is the correct way?

I don't know about correct, but trying to make something do
what you seem to want:

 >>> def pseudo_import(name, s):
 ...     class pseudo_module:
 ...         def __repr__(self): return '<pseudo_module %s>' % self.__name__
 ...     tmp = pseudo_module()
 ...     tmp.__dict__['__name__'] = name
 ...     exec s in tmp.__dict__
 ...     return tmp
 ...
 >>> a = """\
 ... class nasenbaer:
 ...             def singt(self):
 ...                     print "tralala"
 ... """
 >>>
 ==->> Note that you need a self argument (which I added) for a method,
       even if you don't use it explicitly. 

 >>> fa = pseudo_import('file_a', a)
 >>> grail = fa.nasenbaer()
 >>> grail.singt()
 tralala
 >>> fa
 <pseudo_module file_a>
 >>> fa.nasenbaer
 <class file_a.nasenbaer at 0x007A9FD0> 


Not tested any more than you see here, so caveat whatever ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list