Home > Software design >  How to set constants in module by function and use it in another function in python?
How to set constants in module by function and use it in another function in python?

Time:12-26

I want to get in print A2. What is the best way to do that? (for any numbers and types of constants):

VAR1=1
VAR2=2

def choose_var(variation):
    if variation == 1:
        VAR1 = "A"
        VAR2 = 2
    elif variation ==2:
        VAR1 = "B"
        VAR2 = 3 
        
def get_some_stuff():
    return str(VAR1   VAR2)
    
choose_var(1)
print(get_some_stuff())

without passing VAR1 and VAR2 to get_some_stuff()

CodePudding user response:

You need to make both variables global, by default they're local to the method

def choose_var(variation):
    global VAR1, VAR2
    if variation == 1:
        VAR1 = "A"
        VAR2 = 2
    elif variation == 2:
        VAR1 = "B"
        VAR2 = 3

And fix the concatenation between int and str

def get_some_stuff():
    return f"{VAR1}{VAR2}"
  • Related