Home > Mobile >  Using variables in multiple python files
Using variables in multiple python files

Time:11-17

I am trying to use variables created in one file and still use them in another file without having to run all of the code from the first file.

Would I be better off saving the variables to a text file and calling the text file in my second python file?

Ex. File #1

name = input('What is your name')
job = input('How do you earn your money')
user_input = name, job

File #2 I want to be able to call the input from the first file for name without having to import all of rest of the code in file #1

CodePudding user response:

I think the answer depends on the nature of the variables you want to share between files.

For your case, I think a reasonable solution might be to import one module into another, e.g.

# File1.py
# ...
def name_input():
  name = input('What is your name')
  return name

def job_input():
  job = input('How do you earn your money')
  return job
# ...

And in another file:

# File2.py
from File1 import name_input
# ...
name = name_input()
# ...

Though when the module is imported, the whole thing is executed (e.g. appending name = name_input() to File1.py and running File2.py, you'll be asked for your name twice). See the Python docs on modules for more information.

An alternative, as you suggested in your question would be to store the variable outside of your Python code files.

This can be done either through environment variables, text files (and reading and parsing whatever format you have it stored in), or INI-like files using Python's configparser.

CodePudding user response:

Other answer is good advice for someone learning Python. But, I will answer the question:

Would I be better off saving the variables to a text file and calling the text file in my second python file?

Maybe "No". If it is about Python variables, using pickle might be a better alternative.

See the docs.

Example based on other SO answer:

import pickle

name = input('What is your name')
job = input('How do you earn your money')
user_input = name, job

with open('filename.pickle', 'wb') as handle:
    pickle.dump(user_input , handle)

with open('filename.pickle', 'rb') as handle:
    user_input_unpickled = pickle.load(handle)

print(user_input == user_input_unpickled )

Another option is to use JSON or whatever data format is better to store the data (csv, npz, hdf5, parquet, etc).

  • Related