0

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 ?

1
  • Please look up "dynamic programming". This is not it. Commented Sep 5, 2022 at 13:26

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.