I have a variable like YEAR = 2022 Now I want to make a automate variable like Sales_Report_'YEAR's value(2022). How can I create this type of dynamic variable name in python ?
Asked
Active
Viewed 95 times
1
-
Please look up "dynamic programming". This is not it. – molbdnilo Sep 05 '22 at 13:26
3 Answers
1
You can use vars() or globals() if you want to add a new variable to the module's namespace
vars()['Sales_Report_YEAR'] = 2022
globals()['Sales_Report_MONTH'] = 11
If you want to add a new variable to an instance of a class, you can use setattr()
class MyClass:
pass
instance = MyClass()
setattr(instance, 'Sales_Report_YEAR', 2022)
And you also can use setattr() for add a variable to the module
import sys
thismodule = sys.modules[__name__]
setattr(thismodule, 'Sales_Report_YEAR', 2022)
0
Don't do that. Create a dictionary with years for keys:
YEAR = 2022
SALES_REPORTS = {}
SALES_REPORTS[YEAR] = "Whatever you want here as a report"
You could create a container class and do some magic with it, but for most cases dictionary would be enough.

Nikolaj Š.
- 1,457
- 1
- 10
- 17
0
You can use a dictionary to create dynamically key names and associate the value you need.
sales_reports = {}
x = 0
while x < 10:
# Calculating the year
year = (current year)
# Creating the key name
key_name = 'Sales_Report_' + str(year)
# Calculating data_report
data_report = (calculating report data)
# Appending the value and the key name into the dictionary and assigning the appropriate data report to it
sales_reports[key_name] = data_report
# Increasing the value of x to keep iterating until the value is equal with 10
x = x + 1
You can try and use other data structures like python collections.

devblack.exe
- 428
- 4
- 17