Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you initialize a global variable only when its not defined?

I have a global dictionary variable that will be used in a function that gets called multiple times. I don't have control of when the function is called, or a scope outside of the function I'm writing. I need to initialize the variable only if its not initialized. Once initialized, I will add values to it.

global dict
if dict is None:
    dict = {}

dict[lldb.thread.GetThreadID()] = dict[lldb.thread.GetThreadID()] + 1

Unfortunately, I get

NameError: global name 'dict' is not defined

I understand that I should define the variable, but since this code is called multiple times, by just saying dict = {} I would be RE-defining the variable every time the code is called, unless I can somehow check if it's not defined, and only define it then.

like image 265
user353877 Avatar asked Mar 17 '17 15:03

user353877


2 Answers

Catching the error:

try:
    _ = myDict
except NameError:
    global myDict
    myDict = {}

IMPORTANT NOTE:

Do NOT use dict or any other built-in type as a variable name.

like image 184
Adirio Avatar answered Oct 11 '22 12:10

Adirio


A more idiomatic way to do this is to set the name ahead of time to a sentinel value and then check against that:

_my_dict = None

...

def increment_thing():
    global _my_dict
    if _my_dict is None:
        _my_dict = {}
    thread_id = lldb.thread.GetThreadID()
    _my_dict[thread_id] = _my_dict.get(thread_id, 0) + 1

Note, I don't know anything about lldb -- but if it is using python threads, you might be better off using a threading.local:

import threading

# Thread local storage
_tls = threading.local()

def increment_thing():
    counter = getattr(_tls, 'counter', 0)
    _tls.counter = counter + 1
like image 38
mgilson Avatar answered Oct 11 '22 12:10

mgilson