webnub
webnub

Reputation: 41

Changing value and importing - Doesn't save new value

I'm using latest python version; I have a simple function in one file, then another file calls that function. Problem is the variable from function isn't printed.

file1.py:

var = "one"
def first():
    global var
    if smt == True:
        var = "1"
    else:
        var = "W"

file2.py:

from file1 import *
first()
print(var)

This is simplified version because I have more irrelevant code, but the problem is still the same, my variable doesn't change for some reason.

Upvotes: 1

Views: 160

Answers (1)

Julian Camilleri
Julian Camilleri

Reputation: 3095

The practice of using import * is usually discouraged; due to the fact that it might be prone to namespace collisions, inefficient if the import is huge et cetera.

I would personally go for an explicit import: from file1 import first

I also believe that you have the wrong idea of what global is. This might help:

In the first case the global keyword is pointless, so that is not correct. Defining a variable on the module level makes it a global variable, you don't need to global keyword.

The second example is correct usage.

However, the most common usage for global variables are without using the global keyword anywhere. The global keyword is needed only if you want to reassign the global variables in the function/method.

Keep in mind that you do not have var in file2.py by simply using global keyword; if you'd like to access the variable var you can use something like:

In file1.py:

var = "one"


def first():
    global var

    var = "1"

In file2.py:

import file1 

file1.first()
print(file1.var)

Upvotes: 1

Related Questions