Python Forum
local namespace vs. global namespace
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
local namespace vs. global namespace
#1
Output:
globals()['pv'] = <function pv at 0x7f303a969268> Traceback (most recent call last):  File "launch.py", line 760, in <module>    result=main(argv)  File "launch.py", line 386, in main    print('pv =',repr(pv),file=stderr) UnboundLocalError: local variable 'pv' referenced before assignment lt1/ph_use1 /home2/ph_use1 12> head -n390 launch.py|tail        print(file=stderr)        print('globals() =',repr(sorted(globals().keys())),file=stderr)        print('globals() =',repr(sorted(globals().items())),file=stderr)        print(file=stderr)        print("globals()['pv'] =",repr(globals()['pv']),file=stderr)        print('pv =',repr(pv),file=stderr)        pv('arg','parts')        name = 'xy'        if arg[0] == '@':            name, value = 'se', arg[1:]
i am defining a function named "pv" in the global namespace, where they usually get defined, but in this case, it is there, but not being found.  the exception "UnboundLocalError: local variable 'pv' referenced before assignment" has the word local, twice, suggesting that this is happening in some context where it knows it is only going to the local namespace and ignoring the global namespace.  what am i doing wrong?  i want the normal behavior of looking up names in both local an global namespaces.


FYI, the function is defined in this code, not imported from a module.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Can you provide a minimal snippet that reproduces the problem?
Reply
#3
no,  i have tried to re-create the problem but all other code attempts work correctly. i am wanting to understand where this particular message comes from. the message itself is suspicious.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
If you are running cpython, you will probably find the error is generated in
one of the following files:
ceval.c
compile.c
memoryobject.c
symtable.c
(or one of their include files)
Reply
#5
i found code in my big script (some 700 lines) that when removed, fixed it.  that code was a conditional re-def of pv() to do nothing.  it did not meet the condition in my runs and so, the function did not get redefined.  because the code (technically an assignment) existed, python (cpython?) considered that name to be local, so any reference would not look further to the global namespace when it didn't find it in the local namespace.

the following is an example (try it):
x = 6
def main():
   if False:
       x = 7
   print(x)
main()
do you expect to get 6?  you won't

FYI, pv() is a debugging tool in my script (it prints a variable given its name).  that re-def code was intended to make it do nothing if the "nodebug" environment variable was set (to any value).  that way i could easily run the script without all those debug messages whenever i wanted to.

more reading: http://eli.thegreenplace.net/2011/05/15/...-in-python
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#6
Variable x = 6 in global namespace should never exists.
The try to use it some function.
Global variables are bad in any programming language Hand

Terrible:
x = 5
def func_add():
   return x + 6

print(func_add()) #--> 11
The right way,5 is given as as a argument to the function.
def func_add(arg):
   return arg + 6

print(func_add(5)) #--> 11
Reply
#7
(Jul-01-2017, 05:55 AM)Skaperen Wrote: do you expect to get 6?  you won't
No, actually I don't. I expect exactly what happens which is an UnboundLocalError.

Variables aren't bound to the scope of a function upon their specific execution. Having a name that sometimes referred to a local and sometimes a global based on the value of some Boolean would be horrendous; and thankfully it doesn't work this way. If you want the variable local make sure it is defined locally and declare it global if that is what you want (or rather, don't).

I do remember a previous thread that talked more about the why of this in detail and perhaps Casevh will pop up with a more concrete response, but basically, as far as I know the scope of variables is determined at initial runtime, not at the time we think of that code as actually being executed. Your program knows that the way x is being used in that function makes it local despite it never getting assigned.
Reply
#8
Cant say much more than snippsat and mekire already had. If your following PEP 8 guidelines, you shouldnt have a global variable named x. It should be capped to signify it being a global variable and passed into a global function like snippsat described as well as more descriptive. Or you should have global keyword to execute it as such, but as well to blatantly portray it as global. After much of that you usually find your code littered with globals. I usually be rid of globals by encapsulating much of my stuff in classes. I mean there are sometimes when an object is too much, but a lot of times can get rid of the global junk. In your example a main function is too much and you will turn yourself into a java programmer.
Recommended Tutorials:
Reply
#9
the UnboundLocalError problem happens with function definitions, too.

the little 6 line example i showed used a plain assignment just to make the example short and simple.  but since you guys didn't get it and focused on what you could find wrong in the example instead of what it illustrates, i'll make a better version that ends up being longer.  this is an example illustrating the UnboundLocalError problem. although this is bad code, it is a minimalist example of a realistic attempt at debugging.  when coders are trying to debug other problems (not the UnboundLocalError problem), temporarily added code is generally not of concern since it is expected to be remove before release. so here is the 12 line (plus 3 blank lines for easier reading) example showing the UnboundLocalError problem.

from __future__ import print_function
import sys

def debugprint(a):
   print(a,file=sys.stderr)
   return

def main(args):
   if '--nodebug' in args:
       def debugprint(a):
           return
   debugprint('args =',repr(args))
   return 0

exit(main(sys.argv))
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#10
from __future__ import print_function
import sys
 
def debugprint(a):
   print(a,file=sys.stderr)
   return
 
def main(args):
   debugprint('args =',repr(args))
   return 0
 
if __name__ == '__main__':
   args = sys.argv
   if '--nodebug' in args:
       def debugprint(a):
           return
   exit(main(args))
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  It's saying my global variable is a local variable Radical 5 1,172 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Delete all Excel named ranges (local and global scope) pfdjhfuys 2 1,797 Mar-24-2023, 01:32 PM
Last Post: pfdjhfuys
  Global variables or local accessible caslor 4 1,029 Jan-27-2023, 05:32 PM
Last Post: caslor
  How to use global value or local value sabuzaki 4 1,157 Jan-11-2023, 11:59 AM
Last Post: Gribouillis
  'namespace' shorthand for function arguments? shadowphile 5 2,600 Aug-11-2021, 09:02 PM
Last Post: shadowphile
  Global vs. Local Variables Davy_Jones_XIV 4 2,658 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV
  Global - local variables Motorhomer14 11 4,267 Dec-17-2020, 06:40 PM
Last Post: Motorhomer14
  from global space to local space Skaperen 4 2,326 Sep-08-2020, 04:59 PM
Last Post: Skaperen
  [PyKML] Loop through all Placemarks; Remove namespace Winfried 2 3,436 Aug-28-2020, 09:24 AM
Last Post: Winfried
  local / global lists RedWuff 1 1,876 May-26-2020, 03:11 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020