1

I am going to try to be clear. I have a ex.py file I want to import in other py files. In the ex.py file there is a variable that I declare. However, I would like to declare that variable in the other py files.

I have a file ex.py:

variable = 5
whatever = 10 + variable 

For example in an other .py file, I would have:

from ex import whatever
variable = 10
print(whatever)  # whatever object uses the variable

The result from printing whatever will be 15. I would like to have 20 as i declare variable in the new script.

That is to streamline the code so that the same .py file can be used in several other files. Any contribution please.

3
  • 2
    What would be the contents of ex.py and what is the expected output of print(whatever)? Commented Jan 16, 2020 at 2:24
  • 2
    Your code looks fine, as far as it goes. What's the problem? Commented Jan 16, 2020 at 2:26
  • @metatoaster i have edited Commented Jan 16, 2020 at 2:40

1 Answer 1

2

If I understand you correctly, you want whatever to always be variable + 5, right? If you set whatever in the ex.py, its value is fixed to 15 and will not change. In this case you should declare a function which calculates whatever dynamically, like so:

def whatever(variable):
  return variable + 5

If you want to have multiple .py files accessing the same global variable (the other interpretation of your question I can come up with), you might want to have a look at the singleton pattern

Sign up to request clarification or add additional context in comments.

2 Comments

your comment is very useful. however, i am not sure it is the correct answer. I want whatever to always be variable + 10 in that case. variable from the new .py file + 10 from the ex.py file.
@delalma It's not possible to make a variable change automatically like that. There's no way to link variables. If you want something to calculate dynamically, you need a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.