Home > other >  How to set a string before importing a module in python using cli?
How to set a string before importing a module in python using cli?

Time:10-16

code.py:

"""
Chekcs if isset(ABC) or not.
if not set - sets "ABC = 10".
"""
try: ABC
except: ABC = 10

print(ABC)

Outputs => "10"

cli:

python -c "ABC = 20; import code"

Expected to print "20", but it outputs "10".

Is there any possible way to fix this?

CodePudding user response:

Global variables, despite their name, are not global to every part of your program. Each module has its own global namespace, and the same variable can exist, with different values, in different namespaces.

In your example, you're running a script given on the command line. That gets interpreted as the __main__ module in the interpreter. So in __main__, ABC is going to be equal to 20. But when the main module imports code, it has its own namespace. It doesn't see the __main__.ABC value that already exists, so it creates (and prints) its own ABC value.

As for "fixing" the code, I'm not sure it's worth trying. You could probably have code import __main__ and poke around in its namespace, but that seems like a lot of work for a sort of silly goal. There is almost certainly a better way to achieve whatever your actual end goal is (e.g. printing 10), and messing around with other modules' namespaces is unlikely to be it. I suspect this is an XY problem so while I'm dressing your reasonable question about why the code you have behaves the way it does, I don't really think there's a reasonable fix.

CodePudding user response:

I don't think it's possible to set a value before importing the module: When importing a module it does not neccessarily share the same set of variables. The variables inside a module is essentially scoped within its context.

You might be able to set a temporary environmental variable or use sys.argv to get arguments passed via command line but that's very limited (for example, you can't pass on a Python object).

I personally would use a class to achieve similar functions (however you do need to import it first). For example:

In code.py:

class SampleClassName():
    def __init__(self, ABC = 10) -> None:
        print(ABC)
        # The rest of your logic

Then, you can create an instance of this class using:

python3 -c "from code import SampleClassName; instance = SampleClassName(20)"

Notice that here, ABC = 10 defines the default value for ABC. It it's not set, it would be the default value of 10.

You might want to learn more about classes by reading the Python Docs

  • Related