Home > database >  How to use a variable dynamically from an imported module in python 3.8
How to use a variable dynamically from an imported module in python 3.8

Time:02-04

I currently have the following file load.py which contains:

readText1 = "test1"
name1 = "test1"

readText1 = "test2"
name1 = "test2"

Please note that the number will change frequently. Sometimes there might be 2, sometimes 20 etc.

I need to do something with this data and then save it individually.

In my file I import load like so:

from do.load import *
#where do is a directory

I then create a variable to know how many items are in the file (which I know)

values = range(2)

I then attempt to loop and use each "variable by name" like so:

for x in values:
    x = x   1
    textData = readText   x
    nameSave = name   x

Notice I try to create a textData variable with the readText but this won't work since readText isn't actually a variable. It errors. This was my attempt but it's obviously not going to work. What I need to do is loop over each item in that file and then use it's individual variable data. How can I accomplish that?

CodePudding user response:

This is a common anti-pattern that you are stepping into. Every time you think "I'll dynamically reference a variable to solve this problem" or "Variable number of variables!" think instead "Dictionary".

load.py can instead contain a dictionary:

 load_dict = {'readText1':'test1','name1':'test1','readText2':'test2','name2':'test2'}

You can make that as big or small as you want.

Then in your other script

from do.load import *

#print out everything in the dictionary
for k,v in load_dict.items():
    print(k,v)

#create a variable and assign a value from the dictionary, dynamically even
for x in range(2):    
    text_data = load_dict['readText'   x]
    print(text_data)
    x =1

This should allow you to solve whatever you are trying to solve and won't cause you the pain you will find if you continue down your current path.

CodePudding user response:

The file load.py will load only the last variable "readText1" and "name1".

To do what you are asking for, you have to open load.py file as a text file and then iterate over each line the get 2 variables ("readText1" and "name1") in each iteration.

CodePudding user response:

If you are trying to access the variables in the module you've imported, you can use dir.

loader.py

import load

values = dir(load) # All the values in load.py

# to get how many they are
num_vars = len([var for var in module_vars if not var.startswith("__")])
print(num_vars)

# to get their names
var_names = [var for var in module_vars if not var.startswith("__")]
print(var_names)

# to get their values
var_values = [globals()[f"module.{var}"] for var in var_names]
print(var_values)

However, it is unsafe as it may introduce security vulnerabilities to your code. It is also slower. You can use data structures as JNevil has said here, here

  • Related