ljden
ljden

Reputation: 392

Does a global threading Lock need to be declared as global within a method in order to aquire it?

When acquiring a globally instantiated lock inside a method, do we need to declare the lock as global with the global keyword?

If not, why not? Are we not modifying the lock by acquiring it?

I am imaging a case along the lines of:

import threading
name_lock = threading.Lock()
name: str = ""
...

def modify_name(new_name: str):
    global name
    with name_lock:
        name = new_name

...

Upvotes: 0

Views: 607

Answers (1)

furas
furas

Reputation: 142804

All variables created outside functions/classes are automatically global variables.

We use global only inside function(s) to informs function that it has to use external/global variable when you will try to assign new value using = - like name = new_name - if you don't use global then it will create local variable name. But it doesn't need this when you want to change some value/variable inside object - ie. my_list.append(value). And with name_lock doesn't assign new value to variable name_lock but it only executes some methods inside object name_lock which changes inner values.

Upvotes: 1

Related Questions