2

So I have two python files. Let's call them module.py and main.py. module.py looks like this:

name = "bob"
age = 20
def changename():
 name = "tim"

and main.py looks like this:

import module
print(module.name)
module.changename()
print(module.name)

When I run main.py, I get this output, as expected:

>"bob"
>"tim"

However, always having to write module.name will get very time consuming, so I can do from module import *, which imports all of the variables and functions into main.py. However, after changing the code in main.py to this:

from module import *
print(name)
changename()
print(name)

I get this output:

>"bob"
>"bob"

I assume that this is because python imports the values of the variables at the beginning, and then doesn't update them when they get changed by functions within module.py.

My question is, is there a way to nicely import all the functions and variables from a module, but still allow the module to update it's variables?

Thanks in advance!

asked Oct 5, 2014 at 10:34
2
  • 3
    There's no way your first code will return that output. Commented Oct 5, 2014 at 10:37
  • 5
    from module import * is generally bad practice; if you need a shorter name, import module as m. Commented Oct 5, 2014 at 10:37

2 Answers 2

1

I think the best way is to write getter and setter functions in module.py for each global variable you want to share. Like this:

name = "bob"
age = 20
def changename():
 global name # This tells that name is not local variable.
 name = "tim"
def getname():
 return name

Then, you can use these getters in main.py like this:

import module
print(module.getname())
module.changename()
print(module.getname())

But I recommend to import functions one by one to prevent long names. Like this:

from module import changename
from module import getname
print(getname())
changename()
print(getname())

I tested these codes with Python2.7. Define a variable as a global one, before setting a value to it; because setting a value to a variable in a function makes it local (my Python acts in this way!).

matthias_h
11.4k9 gold badges24 silver badges40 bronze badges
answered Oct 5, 2014 at 12:27
Sign up to request clarification or add additional context in comments.

Comments

0

After some testing, I realise that the best way to do this would be to have a third file called 'variables.py' imported as something short, as @jonrsharpe suggested. Both files can change or view variables.name.

answered Oct 5, 2014 at 10:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.