Question regarding naming convention

Steven Taschuk staschuk at telusplanet.net
Tue Jul 1 15:47:57 EDT 2003


Quoth michael:
  [...]
> Is there no way to write a class, such that the statement:
> 
>      import MyClass
> 
> would dynamically import the MyClass class from MyClass.py ?

Not recommended, but:

    # MyClass.py
    import sys
    class MyClass(object):
        pass
    sys.modules['MyClass'] = MyClass

This is a dangerous hack; I'm sure there's lots of code which
expects sys.modules to contain only modules.

Better, if you really want this kind of behaviour, is to write a
custom __import__ function.  See
    <http://www.python.org/doc/current/lib/built-in-funcs.html>

> It just surprises me that there isn't a neater way around this, as 
> Python seems to encapsulate most everything else in a simple way.

It's fairly rare for a module to contain only one entity of
interest to importers.  (StringIO is unusual in this respect.)

Since you're coming from a Java background, you might try thinking
of modules as analogous to leaf-level Java packages.  For example,
where Java has
    java/
        util/
            LinkedList.java
            AbstractList.java
            # etc.
Python would have
    java/
        __init__.py  # to make java a package; probably just has docstring
        util.py  # contains classes LinkedList, AbstractList, etc.

-- 
Steven Taschuk                            staschuk at telusplanet.net
"Our analysis begins with two outrageous benchmarks."
  -- "Implementation strategies for continuations", Clinger et al.





More information about the Python-list mailing list