Why Is the Global Keyword Not Required in This Case

Why isn't the 'global' keyword needed to access a global variable?

The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.

def bob():
me = "locally defined" # Defined only in local context
print(me)

bob()
print(me) # Asking for a global variable

The above will give you:

locally defined
Traceback (most recent call last):
File "file.py", line 9, in <module>
print(me)
NameError: name 'me' is not defined

While if you use the global statement, the variable will become available "outside" the scope of the function, effectively becoming a global variable.

def bob():
global me
me = "locally defined" # Defined locally but declared as global
print(me)

bob()
print(me) # Asking for a global variable

So the above code will give you:

locally defined
locally defined

In addition, due to the nature of python, you could also use global to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.

When do I need to use the global keyword in python

When you do things to foo and foo_foo, you're not changing the reference:

foo = {}
foo['key'] = 'stuff'

foo still refers to the same object as before; it just now contains more data.

bar = ['key', 'value']

This reassigns bar to refer to a new object (the list with two elements).

However, when that line is encountered inside a function, it creates a local reference bar unless you say global bar. In effect, you have two different variables named bar: the global and the local.

Saying global bar tells Python to use the global version of bar rather than creating a new local variable with the same name.

Generally, if you are modifying global variables, you should state global varname for each one to avoid accidentally creating a local.

Or, you can use a class:

class State(object):
def __init__(self):
self.foo = {}
self.foo_foo = {}
self.bar = None

state = State()

def fn():
state.bar = ['key', 'value']

Global dictionaries don't need keyword global to modify them?

The reason is that the line

stringvar = "bar"

is ambiguous, it could be referring to a global variable, or it could be creating a new local variable called stringvar. In this case, Python defaults to assuming it is a local variable unless the global keyword has already been used.

However, the line

dictvar['key1'] += 1

Is entirely unambiguous. It can be referring only to the global variable dictvar, since dictvar must already exist for the statement not to throw an error.

This is not specific to dictionaries- the same is true for lists:

listvar = ["hello", "world"]

def listfoo():
listvar[0] = "goodbye"

or other kinds of objects:

class MyClass:
foo = 1
myclassvar = MyClass()

def myclassfoo():
myclassvar.foo = 2

It's true whenever a mutating operation is used rather than a rebinding one.

In Python, why is list[] automatically global?

It isn't automatically global.

However, there's a difference between rep_i=1 and rep_lst[0]=1 - the former rebinds the name rep_i, so global is needed to prevent creation of a local slot of the same name. In the latter case, you're just modifying an existing, global object, which is found by regular name lookup (changing a list entry is like calling a member function on the list, it's not a name rebinding).

To test it out, try assigning rep_lst=[] in test2 (i.e. set it to a fresh list). Unless you declare rep_lst global, the effects won't be visible outside test2 because a local slot of the same name is created and shadows the global slot.

Why python need global keyword while C/C++ no need?

The fundamental difference is that C and C++ have variable declarations. The location of the declaration determines whether a global is declared.

In Python, you only have assignments. An assignment to a yet-unassigned variable creates that variable. An assignment to an existing variable changes that variable. Hence, without global you couldn't create a local variable if a global variable with that name existed.

Python 3 SyntaxWarning variable used prior to global declaration

No, you can't ignore it and, as of Python 3.6 this will cease to be a SyntaxWarning and instead be updated to an error (SyntaxError). So you better fix it now or face it the prospect of it not executing in future versions (>= 3.6) .

See the docs on the global statement:

Names listed in a global statement must not be used in the same code block textually preceding that global statement.

As you noticed, this isn't a warning that is generated at run-time, it is generated when Python compiles your function object and notices a global statement containing a name (primeRan) that has already been found as local.

You should add the global statement before referencing primeRan here and also do the same for primeList which falls victim to the same issue.

For primeList, though, you can be sneaky and take advantage of the fact that global must be parsed first. In short, switch the condition over so Python parses the global statement for it before the assignment statement:

 def primeGen():
global primeRan
if not primeRan:
global primeSet, primeList, primeCap
primeRan = True
else:
primeList, primeMax = primeList, PrimeCap
# rest as is

Since global is a directive for the parser, this yields the same behavior w/o the warning.

Of course, using globals is not a good practice. I can't see any reason why you'd require using them to be honest, you're always better off (and from a conceptual point of view and execution speed wise) to drop the usage of globals and instead communicate with your function using arguments and return values.

Correct Use Of Global Variables In Python 3

In the first case the global keyword is pointless, so that is not correct. Defining a variable on the module level makes it a global variable, you don't need the global keyword.

The second example is correct usage.

However, the most common usage for global variables are without using the global keyword anywhere. The global keyword is needed only if you want to reassign the global variables in the function/method.

Python: Why is global needed only on assignment and not on reads?

Look at this code:

from module import function

def foo(x):
return function(x)

The name function here is a global. It would get awfully tedious if I had to say global function to get this code to work.

Before you say that your X and my function are different (because one is a variable and the other is an imported function), remember that all names in Python are treated the same: when used, their value is looked up in the scope hierarchy. If you needed global X then you'd need global function. Ick.



Related Topics



Leave a reply



Submit