globals accros modules

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Fri Jan 12 18:22:08 EST 2007


Stef Mientki a écrit :
> Bruno Desthuilliers wrote:
> 
>> Stef Mientki a écrit :
>>
>>> Bruno Desthuilliers wrote:
>>>
>>>> stef a écrit :
>>
>> (snip)
>>
>>>>> but tell them that they are going to loose all their globals ???
>>>>
>>>> It's a feature. Globals are definitively a BadThing(tm).
>>>
>>> yes, I know, but my audience will accept that only in the long term.
>>
>> Unless you clearly explain the benefits... Any code relying on the 
>> existence of a global is:
>> 1/ dependent on the existence of this global
>> 2/ harder to understand
> 
> And you think physicians will believe that ?

Aren't physicians supposed to be somewhat cartesians guys ? FWIW, 
functional languages are mostly used by peoples with a strong 
mathematical background...

> And suppose they believe it, are the willing to stop their research to 
> rethink and rewrite their code ;-)

Not my problem. But anyway, if they really hope to get reliable results, 
they'd better have bug-free programs, and using globals not only 
potentially introduces subtle bugs, but also makes code hardly 
unit-testable...

>>
>> FWIW, I'm currently fixing a simple Delphi program that's using quite 
>> a few globals,
> 
> Then it was certainly not written by a Delphi-guy ;-)

Yes it was. But that does not imply it was written by a competent 
Delphi-guy !-)

(snip)
>>
>> # another.py
>> import myglobs
>> print myglobs.meaning_of_life
>>
>>>
>>> <all other py-files in the project>
>>> import Ugly_MatLab_Globals
>>>
>>> def some_function():
>>>   import Ugly_MatLab_Globals
>>
>>
>> You don't have to reimport it here...
> 
> Then I miss something:

Probably

> TEN = 10
> TWELVE = 12
> def some_function():
>   global TEN
>   TEN = 9

rebinds the 'global' (well... module) name 'TEN'.

>   TWELVE = 11

creates a *local* name 'TWELVE' and bind it to integer 11.

>   print TEN, TWELVE
> 
> some_function()      #will print 9,11
> print TEN, TWELVE    #will print 9,12
> 
> Or am I mistaken ?

You are.

bruno at bibi playground $ cat myglobals.py
a = None
b = None
bruno at bibi playground $ cat useglobals.py
import myglobals

def test():
     myglobals.a = "meaning_of_life"
     myglobals.b = 42

print "myglobals.a : ", myglobals.a
print "myglobals.b : ", myglobals.b
test()
print "myglobals.a : ", myglobals.a
print "myglobals.b : ", myglobals.b

bruno at bibi playground $ python useglobals.py
myglobals.a :  None
myglobals.b :  None
myglobals.a :  meaning_of_life
myglobals.b :  42



More information about the Python-list mailing list