1

I wonder if I can create a new variable and set it as a global variable.

Something like it this:

def f():
    global new_global_var
    if new_global_var is undefined:
        new_global_var = None
    print(new_global_var)    

if __name__ == '__main__':
    f()
    print(new_global_var)

2 Answers 2

1

This seems like something you really shouldn't be doing, but in any case, you can use globals() here (which is essentially like a dictionary of global variables) to accomplish what you want:

def f():
    if "hello" not in globals():
       globals()["hello"] = 3

if __name__ == '__main__':
    f()
    print(hello)
Sign up to request clarification or add additional context in comments.

Comments

1

You can "try" to access the variable. If it does not exist, an exception will be raised. You will create the variable in the exception handler:

def f():
  global new_global_var
  try:
    new_global_var
  except NameError:
    new_global_var = None

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.