Python Forum
Namespace and scope difference
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Namespace and scope difference
#7
To add to what perfringo said, note that Python looks ahead for assignments:

>>> def foo():
...    print(x)
...    x = 3
...    return x + 5
...
>>> x = 5
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'x' referenced before assignment
Python saw that you were going to assign to x in the function, so it decided was in local scope. Then it processed the print call, and couldn't find x in the local scope, and didn't bother to check the further scopes as it otherwise would. If you didn't have the assignment, it would work just like prefringo says.

It is indeed a subtle and twisty topic.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
Namespace and scope difference - by Uchikago - Jul-03-2019, 12:57 PM
RE: Namespace and scope - by ichabod801 - Jul-03-2019, 01:09 PM
RE: Namespace and scope difference - by perfringo - Jul-03-2019, 01:14 PM
RE: Namespace and scope difference - by Uchikago - Jul-03-2019, 01:32 PM
RE: Namespace and scope difference - by ichabod801 - Jul-03-2019, 01:40 PM
RE: Namespace and scope difference - by perfringo - Jul-03-2019, 02:06 PM
RE: Namespace and scope difference - by ichabod801 - Jul-03-2019, 02:25 PM
RE: Namespace and scope difference - by Uchikago - Jul-03-2019, 03:17 PM
RE: Namespace and scope difference - by ichabod801 - Jul-03-2019, 03:31 PM
RE: Namespace and scope difference - by Uchikago - Jul-03-2019, 03:36 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  which namespace? Skaperen 5 243 May-28-2024, 05:38 AM
Last Post: Gribouillis
  How to create a variable only for use inside the scope of a while loop? Radical 10 2,134 Nov-07-2023, 09:49 AM
Last Post: buran
  Library scope mike_zah 2 922 Feb-23-2023, 12:20 AM
Last Post: mike_zah
  Scope of variable confusion Mark17 10 3,028 Feb-24-2022, 06:03 PM
Last Post: deanhystad
  Variable scope issue melvin13 2 1,658 Nov-29-2021, 08:26 PM
Last Post: melvin13
  'namespace' shorthand for function arguments? shadowphile 5 2,709 Aug-11-2021, 09:02 PM
Last Post: shadowphile
  Variable scope - "global x" didn't work... ptrivino 5 3,185 Dec-28-2020, 04:52 PM
Last Post: ptrivino
  Python Closures and Scope muzikman 2 1,929 Dec-14-2020, 11:21 PM
Last Post: muzikman
  [PyKML] Loop through all Placemarks; Remove namespace Winfried 2 3,542 Aug-28-2020, 09:24 AM
Last Post: Winfried
  Block of code, scope of variables and surprising exception arbiel 8 3,568 Apr-06-2020, 07:57 PM
Last Post: arbiel

Forum Jump:

User Panel Messages

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