Global Dictionaries Don't Need Keyword Global to Modify Them

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.

Why is a global dictionary accessible inside a class whereas a global integer variable is not?

Short:

You are trying to change the value of curr_length with curr_length = len(str_) inside a function which looks for a local curr_length variable, and can't find it. It needs the line global curr_length to know that it's a global variable.

As far as why you're wondering as to why a dict object does not need global memoized line, you should read the answer to:
Global dictionaries don't need keyword global to modify them? or Why is the global keyword not required in this case?

EXPLANATION:

In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.

Let's see an example on how a global variable is created in Python.

x = "global"

def foo():
print("x inside :", x)

foo()
print("x outside:", x)

When we run the code, the will output be:

x inside : global
x outside: global

In above code, we created x as a global variable and defined a foo() to print the global variable x. Finally, we call the foo() which will print the value of x.

What if you want to change value of x inside a function?

def foo():
x = x * 2
print(x)
foo()

When we run the code, the will output be:

UnboundLocalError: local variable 'x' referenced before assignment

The output shows an error because Python treats x as a local variable and x is also not defined inside foo().

To make this work we use global keyword

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.

Trying to use a global dict in python3

d += {num2:primes} is ambiguous to python. d is a local on the left hand side and a global on the right hand side. You can fix the problem by putting global d at the top of the function.

def dict_check(num) :
global d
...

global variable in python that doesn't make change in sub function

The global result was outside the scope.

number = int(input("enter your first num: "))
operation = input("enter your operation: ")
second_number = int(input("enter your second num: "))

def cal(num1, op, num2):

def add():
result = num1+num2
return result

def multiply():
result = num1 * num2
return result

def devide():
if not num2 == 0:
result = num1 / num2
return result
else:
result = 'num2 can\'t be zero'
return result

def default():
print("Incorrect option")
switch = {
'+': add,
'*': multiply,
'/': divide
}
return switch.get(op, default)()

print(cal(number, operation, second_number))

Python program that uses global
def method():
# Change "value" to mean the global variable.
# ... The assignment will be local without "global."
global value
value = 100

value = 0
method()

# The value has been changed to 100.
print(value)
100`

Python program that uses nonlocal
def method():

def method2():
# In nested method, reference nonlocal variable.
nonlocal value
value = 100

# Set local.
value = 10
method2()

# Local variable reflects nonlocal change.
print(value)

# Call method.
method()
100

How to update global dictionary in a function

This gets you your final version of dict2, but I'm not sure that multiprocessing buys you anything in terms of performance.

Warning: Python3 alert

import multiprocessing

dict1 = dict( (k,v) for (k,v) in zip(range(0,11),range(50,61)))
dict2={}

def fun1(dct):
key, value, dict2 = dct #unpack tuple
# This code would not update dict2
# dict2.update({value:key})

# return the value and key reversed. I assume this is what you are after.
return {value:key}

if __name__ == '__main__':
p=multiprocessing.Pool(2)

# pass the tuple of (key,value,dict2) into each call of fun1
dict3=p.map(fun1,((key,value,dict2) for key, value in dict1.items()))
p.close()
p.join()

print(dict1) # original dict
print(dict2) # remains empty
print(dict3) # this is a list of the results

for d in dict3:
dict2.update(d)
# Now dict2 is populated
print(dict2)

Output:

{0: 50, 1: 51, 2: 52, 3: 53, 4: 54, 5: 55, 6: 56, 7: 57, 8: 58, 9: 59, 10: 60}
{}
[{50: 0}, {51: 1}, {52: 2}, {53: 3}, {54: 4}, {55: 5}, {56: 6}, {57: 7}, {58: 8}, {59: 9}, {60: 10}]
{50: 0, 51: 1, 52: 2, 53: 3, 54: 4, 55: 5, 56: 6, 57: 7, 58: 8, 59: 9, 60: 10}

Variable scope with dictionaries

You only need global foo when you want to assign to the global name foo. You are not assigning to b_dict; you are assigning to one of its keys, equivalent to b_dict.__setitem__('s', 'lalala'). Both uses of b_dict treat it as a free variable, since there is no local variable named b_dict defined.

The value of a free variable is taken from the closest enclosing scope (in this case, the global scope) where it is defined.



Related Topics



Leave a reply



Submit