[Tutor] import confusion

Marc Tompkins marc.tompkins at gmail.com
Mon Jan 26 06:31:53 CET 2009


On Sun, Jan 25, 2009 at 8:23 PM, Eric Abrahamsen <eric at ericabrahamsen.net>wrote:

> Hi there,
>
> I'm trying to understand how module imports work, and am seeing some
> behavior I don't understand:
>
> >>> import django
> >>> from django import forms
> >>> from forms import DecimalField
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> ImportError: No module named forms
> >>> import django.contrib
> >>> from django.contrib import auth
> >>> from auth import ImproperlyConfigured
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> ImportError: No module named auth
>
>
> So what I'm seeing is that you can import X, then from X import Y, but only
> if Y is another module and not an object. The import chains above work until
> I try to import a class definition. Can someone explain what it is about
> module imports that makes it work this way? And why the unhelpful error
> message?
>

Someone will no doubt phrase this better, but let's take a shot...

1)  You don't need to import django before you import forms; it's
redundant.
2)  You DO need to give Python enough information (i.e. the full name path)
to find the most-specific thing you're trying to import.
2)  "import django" makes the entire django package and all sub-modules
available.  You could then refer to django.forms.DecimalField and
django.contrib.auth.ImproperlyConfigured (for example) in your program, no
further imports needed.
3)  "from django import forms" ONLY imports django.forms, and makes it
available as "forms" (i.e. no need to refer to django.forms) - but not for
further imports; for those you still need to specify the full name.
4)  To import ONLY DecimalField or ImproperlyConfigured, you would do the
following:
from django.forms import DecimalField
from django.contrib.auth import ImproperlConfigured
5)  You can also create aliases:
from django.forms import DecimalField as decField
from django.contrib.auth import ImproperlyConfigured as Oopsie

Hope that helps...
-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090125/1d135352/attachment.htm>


More information about the Tutor mailing list