Q:

Is it possible to permanently change a variable inside a Python script from the same script?

Just hear me out:
I want to pass some arguments to a script from bash: python my_python_script.py set_api <api_key> but I want the api_key to be stored as a permanent variable inside the same script. I'm wondering if that's possible, since I have in mind other options, like I can simply store the variable inside a different file and make sure my script reads that file before anything else.
What is the best/safest approach?

A:

While the method of modifying your source file mentioned by others would probably work, I would highly recommend looking into other solutions such as storing a configuration file with the relevant information that is changing. If you don't want to write this functionality yourself (which can be as simple as a hidden file in the same directory as the script with a single line containing, say, an api key) you can look into solutions such as ConfigParser, using JSON, or even just pickling an object. When you need to access that information, such as the value of an API key, you can read in the configuration file. 
In general, if you need to reference something by a value look into using dictionaries. For instance, if my api key was "abc", instead of accessing foo.abc, I could put a dictionary d = {"abc": value} on foo and access foo.d["abc"]
Again, as mentioned by others, it is generally considered bad practice to write self-modifying code since it can be very hard to read and maintain. If you have the ability to write to the directory with the code file in it, there are rarely good reasons to modify that file over using a configuration/persistent state file.

