[Tutor] confusion about imports

Walter Prins wprins at gmail.com
Mon Jul 9 19:42:03 CEST 2012


Hi Chris

> So, I have to admit, imports have me really confused.  I am trying to break apart a 10,000+ line single file into various files, one for each class, and one containing a whole bunch of functions which are used by a lot of classes.  Some of those functions use calls to methods in a Class.  Even though the Class has been imported, I get a nameError where trying to use the class.  I have read about Classes and packages and modules, but import just has me confused.

How did you import the class?  Or did you perhaps not import the Class
itself, but rather the module containing the class?

Read this article which explains a bit about Python namespaces:
http://is.gd/e8PAZW  (but I note there's a bit of conflation of
"class" and "class instance" going on at the end.)

Also read this page from the Python documentation, section "Python
Scopes and Namespaces": http://docs.python.org/tutorial/classes.html

If a class is defined in a module (e.g. in the namespace of the
module), and you "import module" the module into the your current
namespace, then from within the current namespace you can access the
class with "module.Class".  If however you import the class itself,
e.g. "from module import Class", into your current namespace, then the
Class itself is directly part of your local namespace and you must
therefore access it unqualified as just "Class".

HTH,

Walter


More information about the Tutor mailing list