[Baypiggies] Fwd: A beginner's question on python class

Lincoln Peters anfrind at gmail.com
Tue Feb 21 00:45:09 CET 2012


On Mon, Feb 20, 2012 at 2:02 PM, Yiou Li <liyiou at gmail.com> wrote:
> My question is, since I import a function "sample" from the library
> "random" in myClass, do I have to import "sample" in my main script as
> well?
>
> --- I did a debugging experiment using the following code to see that
> the library "random" was imported at myClassInstance.myFunction(),
> therefore, the answer to my question is -- I don't have to import the
> "random" library in the main script. And the import statement is just
> like a #include statement in C.

Short answer: yes, you have to import random even if another module
you imported already imports random.

Long answer: "import" is similar to "#include", but not identical.  In
general, each .py or .pyc file represents a module, and each import
statement makes the contents of one module available from within the
importing module.  However, unlike #include, the import command
doesn't add the contents of the other module to the importing module's
namespace, but rather creates a reference to it that behaves similarly
to a C++ namespace (e.g. import random; random.shuffle(...)).  One
consequence of this is that if you want to import modules A and B, and
module B already imports module A, you need to either explicitly
import both modules, or you have to refer to module B to get to module
A (i.e. B.A.function instead of A.function).  Most of the time,
importing both modules is the preferred solution.

Note that importing a module multiple times will NOT cause multiple
copies of it to be made in memory; the Python interpreter is smart
enough to recognize that a module has already been imported and will
just create a new reference to it.

Disclaimer: this is a highly simplified explanation, and omits several
nuances of how importing works in Python.  For 99% of Python
development, however, you don't need to worry about those nuances.


Hope this helps.


-- 
Lincoln Peters
<anfrind at gmail.com>


More information about the Baypiggies mailing list