Home > other >  Python module functions to use variables from global env
Python module functions to use variables from global env

Time:05-17

I'm relatively new to Python and am trying to both do something and learn more about how Python works.

I am coming up empty with google, in part I think because I don't know how to correctly describe what I'm trying to do.

My goal is to load a function from a module, which does not take/require arguments, but finds what it needs in the global environment.

This works:

temp = 17

def doubletemp():
    dt = temp * 2
    return dt

doubletemp()

But if I put doubletemp() in a separate file, called steve.py and have this:

steve.py

def doubletemp():
    dt = temp * 2
    return dt

dt.py

import steve

temp = 17

steve.doubletemp()

When I run dt.py, I get an error: NameError: name 'temp' is not defined.

Is there a way around this? A way for the function in Steve.py to look for temp within dt.py's environment?

Thanks!

CodePudding user response:

you could use :

def doubletemp():
    temp = globals()["temp"]
    dt = temp * 2
    return dt

whereby globals() will check your current module, in your case steve.py, but in my opinion this would be a very bad practice. Why don't you just give your variable as parameter in your function, like this :

def doubletemp(t):
    return t * 2

**in steve.py** --> doubletemp(temp)

CodePudding user response:

In Python, using global variables is not really recommended and mostly considered as bad practice, unless you absolutely have to use them.

In your case, just implement parameter passing. Your first example works, because it's all defined in a single file, but it's still not recommended to do it without parameter passing (what you are doing in the first example).

Do it this way instead:

dt.py

    import steve
    temp = 17
    steve.doubletemp(temp)

steve.py

    def doubletemp(temperature):
        double_temp = temperature * 2
        return double_temp

And just so you know, temp and temperature are 2 different variables. Also, if you want to have everything in a single file, it's very much recommended to have parameter passing:

    def doubletemp(temperature):
        dt = temperature * 2
        return dt

    temp = 17
    doubletemp(temp)
  • Related