Note that there are some explanatory texts on larger screens.

plurals
  1. POAutoload in Python
    primarykey
    data
    text
    <p>In the past I've used perl's AUTOLOAD facility for implementing lazy loading of symbols into a namespace, and wanted the same functionality in python. </p> <p>Traditionally the closest you appear to be able to get is to use a class and a <code>__getattr__</code> class to achieve this sort of thing. However I've also tried rummaging around in <code>sys.modules</code>, and come up with this:</p> <pre><code># mymod.py def greet(greeting="Hello World"): print greeting class autoload(object): def __init__(self, __name__): super(autoload, self).__init__() self.wrapped_name = __name__ self.wrapped = sys.modules[__name__] def __getattr__(self, name): try: return getattr(self.wrapped, name) except AttributeError: def f(): greet(name+" "+self.wrapped_name) return f if __name__ != "__main__": import sys sys.modules[__name__] = autoload(__name__) </code></pre> <p>This does work the way I'd like from a user perspective:</p> <pre><code>~&gt; python Python 2.5.1 (r251:54863, Jan 10 2008, 18:01:57) [GCC 4.2.1 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import mymod &gt;&gt;&gt; mymod.hello() hello &gt;&gt;&gt; from mymod import Hello_World &gt;&gt;&gt; Hello_World() Hello_World </code></pre> <p>But it strikes me - is there a standard approach that people tend to use for autoloading in python?</p> <p>Secondly, a question for experienced python developers really is "does this strike you as good or bad practice"? I'm a reasonably experienced python developer, and it strikes me as really useful, but it strikes me as borderline and interested in whether this can be viewed as good practice, bad practice or similar.</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload