name space problem

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Oct 24 07:15:59 CEST 2007


En Tue, 23 Oct 2007 23:34:38 -0300, BBands <bbands at gmail.com> escribió:

> On Oct 23, 4:20 pm, marek.ro... at wp.pl wrote:

> I was trying to understand why it worked when written in, but not when
> included.

Not *included*. When you do `import doStuff` you dont "include" anything;  
this is what happens (simplified):

- Look into the already loaded modules; if a "doStuff" module already  
exists, return it.
- Search some directories on disk, looking for "doStuff.py". If found,  
load and execute it (remember that import, class, def, etc. are  
*executable* statements in Python).
- If still not found, raise an error.

So, after successful execution of `import doStuff`, you have a new name  
`doStuff` that refers to the imported module. It's not the "contents" of  
doStuff that gets "included" into the current module; doStuff exists by  
itself as a separate module, and you get a name that refers to it.

>> I think the right solution would be not to use 'a' as a global
>> variable, but rather to pass it as an explicit parameter to the
>> function.
>
> Does doing this make a copy of a?

No! Python never makes a copy unless you explicitely say so.

>> In module doStuff:
>>
>> def doStuff(a):
>>     # some calcs
>>     a.b = 0
>>
>> In the main module:
>>
>> import doStuff
>> # ...
>> doStuff.doStuff(a)
>
> In my real ap a is quite large...

It doesn't matter. `a` is just a name, referencing an object. It's never  
"copied" unless you specifically ask for it. Passing objects as arguments  
is absolutely common, and the right thing to do in this case; it's  
efficient, don't worry...

-- 
Gabriel Genellina




More information about the Python-list mailing list