Python Using Variables from Another File

python using variables from another file

You can import the variables from the file:

vardata.py

verb_list = [x, y, z]
other_list = [1, 2, 3]
something_else = False

mainfile.py

from vardata import verb_list, other_list
import random

print random.choice(verb_list)

you can also do:

from vardata import *

to import everything from that file. Be careful with this though. You don't want to have name collisions.

Alternatively, you can just import the file and access the variables though its namespace:

import vardata
print vardata.something_else

Importing variables from another file?

from file1 import *  

will import all objects and methods in file1

Access variable from a different function from another file

You can access the value of a variable in a function by 1) returning the value in the function, 2) use a global variable in the module, or 3) define a class.

If only want to access a single variable local to a function then the function should return that value. A benefit of the class definition is that you may define as many variables as you need to access.

1. Return value

def champs_info(champname:str, tier_str:int):  
...
tier = tier_access.text
return tier

2. global

tier = None
def champs_info(champname:str, tier_str:int):
global tier
...
tier = tier_access.text

Global tier vairable is accessed.

from mypythonlib import myfunctions

def test_champs_info():
myfunctions.champs_info("abomination", 6)
return myfunctions.tier

print(test_champs_info())

3. class definition:

class Champ:
def __init__(self):
self.tier = None
def champs_info(self, champname:str, tier_str:int):
...
self.tier = tier_access.text

test_functions.py can call champs_info() in this manner.

from mypythonlib import myfunctions

def test_champs_info():
info = myfunctions.Champ()
info.champs_info("abomination", 6)
return info.tier

print(test_champs_info())

How to import variables from another file AFTER the program has started in python?

You could just use

with open(file, "r") as f:
data = f.read().splitlines()

to read the data, assuming every variable is on its own line. This will read in all variables in the file file as a list called data containing each file line as one entry.

Note that this will read all variables in as strings, so you may have to cast to different types before actually using the values.

Import variables from another .py file

You should use any definitions from another python file like this:

import module
module.variable = 5
module.class()
module.function()

or You can do:

from module import variable, class, function
variable = 5
class()
function()

from module import * is not good practice.
If you hate typing, you can give another name:

from module import variable as var
var = 5


Related Topics



Leave a reply



Submit