# Dynamic variable name

**URL:** <https://discuss.python.org/t/dynamic-variable-name/18585>\
**Category:** Python Help\
**Tags:** help\
**Created:** [August 30, 2022, 5:47am UTC](https://discuss.python.org/t/dynamic-variable-name/18585 "2022-08-30T05:47:53Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![sandeep123](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/sandeep123/32/8675_2.png) [@sandeep123](https://discuss.python.org/u/sandeep123)\
**Post date:** [August 30, 2022, 5:47am UTC](https://discuss.python.org/t/dynamic-variable-name/18585/1 "2022-08-30T05:47:53Z")

</div>

Suppose i have to set

```auto
q_variable = 0
a_variable = 0

def stats(choice):
     choice + '_variable' += 1

stats('q')

```

Here after adding the choice + ‘\_variable’ will become string.  
If i want to change the q\_variable or the a\_variable depending on the choice we provide to the function.  
How do we do that?

---

<div class="post-metadata">

**Author:** ![abessman](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/abessman/32/8367_2.png) [@abessman](https://discuss.python.org/u/abessman)\
**Post date:** [August 30, 2022, 5:52am UTC](https://discuss.python.org/t/dynamic-variable-name/18585/2 "2022-08-30T05:52:27Z")

</div>

Use a dictionary;

```python
variables = {"q": 0, "a": 0}

def stats(choice):
    variables[choice] += 1

stats("q")

```

---

<div class="post-metadata">

**Author:** ![vainaixr](https://avatars.discourse-cdn.com/v4/letter/v/5f8ce5/32.png) [@vainaixr](https://discuss.python.org/u/vainaixr)\
**Post date:** [August 30, 2022, 7:57am UTC](https://discuss.python.org/t/dynamic-variable-name/18585/3 "2022-08-30T07:57:59Z")

</div>

maybe not use `vars` as the name of the dictionary, as it is a builtin on its own.

---

<div class="post-metadata">

**Author:** ![abessman](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/abessman/32/8367_2.png) [@abessman](https://discuss.python.org/u/abessman)\
**Post date:** [August 30, 2022, 7:59am UTC](https://discuss.python.org/t/dynamic-variable-name/18585/4 "2022-08-30T07:59:13Z")

</div>

Good point, changed it to `variables`.

---

<div class="post-metadata">

**Author:** ![aivarpaalberg](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/aivarpaalberg/32/9457_2.png) [@aivarpaalberg](https://discuss.python.org/u/aivarpaalberg)\
**Post date:** [August 30, 2022, 10:43am UTC](https://discuss.python.org/t/dynamic-variable-name/18585/5 "2022-08-30T10:43:47Z")

</div>

> [@sandeep123](#):
>
> If i want to change the q\_variable or the a\_variable depending on the choice we provide to the function.  
> How do we do that?

As suggested, use dictionary or any other suitable data structure. Because if you create variables dynamically you probably want to access them dynamically as well. Now you have two problems.

You can do what you want but you must consider very-very seriously whether is it what you actually need. As it happens, globals are also kept in dictionary so you can always make your life exciting:

```auto
>>> a_variable = 1
>>> q_variable = 2
>>> def stats(choice):
... globals()[f'{choice}_variable'] +=1
...
>>> stats('a')
>>> a_variable
2
>>> stats('a')
>>> a_variable
3
>>> stats('q')
>>> q_variable
3

```

---

<div class="post-metadata">

**Author:** ![rob42](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/rob42/32/8218_2.png) [@rob42](https://discuss.python.org/u/rob42)\
**Post date:** [August 30, 2022, 12:03pm UTC](https://discuss.python.org/t/dynamic-variable-name/18585/6 "2022-08-30T12:03:44Z")

</div>

I’m somewhat curious: why would you want to do this? What is your use case?

It seems to me that, if scaled up, this would have a detrimental effect on the readability of the code script as well as a complicated way to code. If things seem to be complicated in Python, there’s usually a better (or a less complicated) way to write the code.

---

<div class="post-metadata">

**Author:** ![Skaperen](https://avatars.discourse-cdn.com/v4/letter/s/b3f665/32.png) [@Skaperen](https://discuss.python.org/u/Skaperen)\
**Post date:** [September 1, 2022, 12:52am UTC](https://discuss.python.org/t/dynamic-variable-name/18585/7 "2022-09-01T00:52:43Z")

</div>

> [@abessman](#):
>
> Good point, changed it to `variables`

how about something more meaningful, such as `choices`.

---

<div class="post-metadata">

**Author:** ![abessman](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/abessman/32/8367_2.png) [@abessman](https://discuss.python.org/u/abessman)\
**Post date:** [September 1, 2022, 5:47am UTC](https://discuss.python.org/t/dynamic-variable-name/18585/8 "2022-09-01T05:47:30Z")

</div>

I mean, sure, in an actual application you should never name a variable `variables`. This is just an example, and without knowing what the purpose of the variable is it’s not possible to select a good name.

---

<div class="post-metadata">

**Author:** ![andand](https://avatars.discourse-cdn.com/v4/letter/a/ce73a5/32.png) [@andand](https://discuss.python.org/u/andand)\
**Post date:** [April 21, 2023, 11:36am UTC](https://discuss.python.org/t/dynamic-variable-name/18585/9 "2023-04-21T11:36:10Z")

</div>

I can provide some use case.

Lets assume you are testing Windows Calculator as a desktop app.

You generate test data and need to verify that sum or prod works.

Every time calculation is done result is displayed in a window that is an object.

Object name is

```auto
Aliases.Microsoft_WindowsCalculator.Calculator.NavView.LandmarkTarget.Display_is_XXXX.TextContainer.NormalOutput

```

Where XXXX is the result of your calculation. E.g. 2 or 5 or 2023.

And you need to access this object to verify

When you try to get properties of a “parent” object

```auto
Aliases.Microsoft_WindowsCalculator.Calculator.NavView.LandmarkTarget

```

with a dir() function you get this

```auto
['_IDispatchWrapper __cookie', '_IDispatchWrapper__ hasOwnAttr', '_IDispatchWrapper __raiseBadParamCount', '_IDispatchWrapper__ raiseObjectIsNotCallable', '_IDispatchWrapper __raiseObjectIsNotConvertableToType', '_IDispatchWrapper__ raiseObjectIsNotIndexable', '_IDispatchWrapper __safeEval', '__ bool __', '__ call __', '__ callmethod __', '__ class __', '__ del __', '__ delattr __', '__ dict __', '__ dir __', '__ doc __', '__ eq __', '__ float __', '__ format __', '__ ge __', '__ getattr __', '__ getattribute __', '__ getitem __', '__ getprop __', '__ gt __', '__ hash __', '__ init __', '__ init_subclass __', '__ int __', '__ le __', '__ lt __', '__ module __', '__ ne __', '__ new __', '__ reduce __', '__ reduce_ex __', '__ repr __', '__ setattr __', '__ setitem __', '__ setprop __', '__ sizeof __', '__ str __', '__ subclasshook __', '__ weakref__']

```

I am not an expert in Python so if someone knows how to you solve this problem with a dictionary (of reasonable size) or some other way please share.

---

<div class="post-metadata">

**Author:** ![ajoino](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/ajoino/32/6907_2.png) [@ajoino](https://discuss.python.org/u/ajoino)\
**Post date:** [April 21, 2023, 12:44pm UTC](https://discuss.python.org/t/dynamic-variable-name/18585/10 "2023-04-21T12:44:53Z")

</div>

When you need this highly dynamic sort of program, you should reach out for the `hasattr`, `getattr`, and `setattr` functions. Note that they only work in a class:

```python
class Foo:
    x_var = 10
    y_var = 25

foo = Foo()

# equivalent to `foo.x_var = foo.y_var + 5`
setattr(foo, "x_var", getattr(foo, "y_var") + 5)

print(foo.x_var) # 30

```

They are extremely handy when necessary, but somewhat unergonomic to work with

---

<div class="post-metadata">

**Author:** ![robvh](https://avatars.discourse-cdn.com/v4/letter/r/a3d4f5/32.png) [@robvh](https://discuss.python.org/u/robvh)\
**Post date:** [February 6, 2024, 2:19pm UTC](https://discuss.python.org/t/dynamic-variable-name/18585/11 "2024-02-06T14:19:39Z")

</div>

If you have an object that support vars(), like a class or an instance, you can use vars() to access variables with a dynamic name, like so:

```python
class Foo:
  def __init__ (self):
    self.x_var = 10
    self.y_var = 25

  def incr(self,varpref):
    vars(self)[f"{varpref}_var"] += 1

foo = Foo()

for i in range(10):
  foo.incr("x")

print(foo.x_var)
>>> 20

```

Setattr overwrites the atribute, but the vars() function or getattr support methods on the (class) properties:

```python
class Logger:
  def __init__ (self):
    self.x_var = []
    self.y_var = []

  def msg(self,varpref,logmsg):
    vars(self)[f"{varpref}_var"].append(logmsg)

  def altmsg(self,varpref,logmsg):
    getattr(self,f"{varpref}_var").append(logmsg)

foo = Logger()

for i in range(10):
  foo.msg("y",f"logmessage {i}")

print(foo.x_var)  
>>> []
print(foo.y_var)  
>>> ['logmessage 0', 'logmessage 1', 'logmessage 2', 'logmessage 3', 'logmessage 4', 'logmessage 5', 'logmessage 6', 'logmessage 7', 'logmessage 8', 'logmessage 9']

```
