Question regarding naming convention

John J. Lee jjl at
Tue Jul 1 19:17:06 CEST 2003

michael <spam.trap at> writes:
> Yeah, thanks for the quote. Unfortunately, this still leaves me with
> syntax that's a bit unfriendly. Taking the StringIO class as an
> example, I can either write:
>      import StringIO
>      s = StringIO.StringIO()
> or:
>      from StringIO import StringIO
>      s = StringIO()
> Both of the above seem to overcomplicate the syntax. Of the two, I

Well, one is simpler when you only use StringIO.StringIO once or
twice, and the other is simpler when you use it lots of times.
Really, there are two issues, I suppose.  First, the second form has
the convenience of shorter names.  Second, the first form is useful
where somebody reading your code would otherwise have to keep
referring to your imports to see where names came from, or might be
confused by similarly-named classes in different modules.  Third, ease
of switching names -- sometimes it's convenient to be able to swap

from StringIO import StringIO


from cStringIO import StringIO

And have your code work unchanged.  OK, three issues.

A fourth issue is that it's nice not to mix the two styles, to avoid
confusing readers.

> prefer the second, but I'm sure I've read on that the
> from..import.. version is not a preferred way of doing things.

Nothing un-preferred about 'from foo import bar'.  What is discouraged
is 'from foo import *' (that's a literal *, if you haven't seen that
syntax before -- see the tutorial).  It is useful sometimes, though.
In PyQt, for example.

> Is there no way to write a class, such that the statement:
>      import MyClass
> would dynamically import the MyClass class from ?

Well, maybe (I'm vaguely aware that there's an import hook of some
kind).  *Nobody* would thank you for it, other than as a joke.

> 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.

Modules are useful, and explicit is better than implicit.


More information about the Python-list mailing list