Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference

dn PythonList at DancesWithMice.info
Wed Mar 6 20:10:11 EST 2024


On 7/03/24 05:28, Jacob Kruger via Python-list wrote:
...
> So, yes, know this comes across like some form of a scam/joke, or 
> list-garbage, since it doesn't make any sense to me at all, but still 
> just wondering if missing something, or should I shift over to 3.12 to 
> see if if works differently, or just try reinstalling 3.11 from scratch, 
> or should I retry the above in something like the VS code console, or a 
> different python console, etc.?
Some of the facts, such as HOW the code was being executed were missing 
(see earlier request for a cut-down scenario, AND reports from others 
saying 'but it works for me').

The idea of importing a module into the REPL and then (repeatedly) 
manually entering the code to set-up and execute is unusual (surely type 
such into a script (once), and run that (repeatedly). As you say, most 
of us would be working from an IDE and hitting 'Run'. Am wondering why 
you weren't - but it's not important.

That said, the REPL is the perfect place to learn, experiment, and 
prototype - particularly when compared with the facilities of other 
language's eco-systems. The entirety of the on-line Tutorial cannot be 
wrong! (although, after a quick review, I've failed to see where the 
Tutorial mentions the usual development mode, apart from two very brief 
asides (the most useful is almost at the very end(?)) - but then (as 
they say) the objective is to show the language!

The lesson-learned is that there are different 'environments' and 
different ways of building the environment in which the code will run. 
That's a valuable lesson, and full of subtlety!

Glad to see that comparing id()s was useful - for diagnosis but not 
solution. Other tools might include the locals() and globals() 
functions. You may also have detected that many of us try to avoid 
globals and the implicit assumptions about the behavior of mutable 
collections (eg lists) when treated as 'global'. Then there are 
"closures", the "LEGB" rule, namespaces, scope, and ...

-- 
-- 
Regards,
=dn


More information about the Python-list mailing list