Search code examples
pythonpython-3.xglobal-variables

Changing global variable mentioned on a dictionary


I'm trying to change global variable from a nested function, the target variable is also mentioned on another global variable, here's the code I used:

import requests

codomain = 'line.me'
requ = { "Host": control_domain, "DNT":  "1", "Accept-Language": "*", "Accept": "*/*", "Accept-Encoding": "*", "Connection": "keep-alive", "Upgrade-Insecure-Requests": "1" }

def menu():
    ans=input(" Choose : ")
    if str(ans)=="1":
        ...
        opti=input(" Choose Option :  ")
        if str(opti)=="1":
            def text():

                print("1. Insert Target Domain")
                print("2. Leave it as default")
                print("")
                ansi=input(" Choose Option : ")
                if str(ansi)=="1":
                    codomain=input(" Domain : ")
                    print(f"{codomain}" + " Selected as Domain")
                else:
                    pass

                print(" Outside " + f"{codomain}")
                print(" Check " + f"{requ}")
                r=requests.get("http://linecorp.com",headers=requ)
            text()
menu()

Specifically, the problem is located at global variable itself:

codomain="line.me"
requ={ "Host": codomain }

I want to add user input whether the codomain is changed by the user or left as default; which is line.me. I have tried to explicitly cast the changed variable using global and nonlocal.

global codomain
codomain=input("Input Domain:")

But the above codes doesn't change the target codomain inside requ variable, this proven when printing the variable:

print(codomain) #It prints user-input
print(requ) #Codomain inside requ still prints default line.me

I'm trying another workaround by directly accessing globals for codomain inside requ:

host="line.me"
codomain=str(globals,["host"])
requ={ "Host": codomain }

The following results in dict error as probably dict can't pass item directly.


Solution

  • It looks like, i got a little confused on how the dict works. The dict codomain variable is reserved and not follows the codomain changes. Turns out it's easy to fix.

    ### Instead of accessing ```globals```
    codomain=str(globals,["Host"])
    
    ### Just change the ```dict``` directly
    requ["Host"]=codomain