0

I want to access the python variable from config file dynamically like below.

config file:

total_var_count = 4
var1=1
var2=2
var3=3
var4=4

main_file.py

import config as cf
for variable_no in range(1,int(cf.total_var_count)+1):
print(cf.var+str(variable_no))

another method I have tried:

new_var ='var'+str(1)
print(cf.new_var) # which is also not working.

I have tried the above methods to access but its not working. Could someone tell me how I can access the variable from config file dynamically?

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    Use a list instead of four separate variables. – khelwood Aug 31 '21 at 23:02
  • Usually a list or dict is a better approach than a bunch of similar variables. If you really need this you can use "getattr" because variables in a module can be handled like attributes of that module. – Michael Butscher Aug 31 '21 at 23:02
  • In addition to the advice in the linked duplicate, *don't use a .py file to configure data values*. Use an actual data file with a standardized format (for example, JSON or CSV), and the corresponding tools to read it in (for example, the standard library `json` and `csv` modules respectively). That way, you don't have to *trust* the configuration data not to contain malicious code. – Karl Knechtel Aug 31 '21 at 23:23

1 Answers1

0

You can use getattr() for this:

main_file.py

import config as cf

new_var = 'var' + str(1)
print(getattr(cf, new_var))

The attribute is here the variable of the imported module.

Sven Eberth
  • 3,057
  • 12
  • 24
  • 29
  • While correct, we already have duplicate questions that explain `getattr` inside and out; and we also *strongly discourage* these approaches because everyone who has a valid reason to use them is not in a position to ask a question this basic on Stack Overflow. Which is why we link them to the duplicate I have chosen, instead. – Karl Knechtel Aug 31 '21 at 23:24