-1

I am reading How can you dynamically create variables in Python via a while loop? and I don't understand the word "dynamically".

Does it refer to the fact that the variable should be created after the pyc has been created?

In the following code:

x = 3 
globals()['y'] = 4

Is y created dynamically?

Community
  • 1
  • 1
usual me
  • 8,338
  • 10
  • 52
  • 95

1 Answers1

0

Yes, in your example y is created dynamically. Strictly speaking, it has nothing to do with it being created before or after the .pyc file. It has to do with it being created as a side effect of some other code being run.

You can dynamically create variables in other ways, too. For example, with exec:

exec("x=42")
print(x)

While such things are possible, they should generally be avoided because it makes your code harder to understand.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • 1
    In this case, at least the name of the variable is hard-coded, and in theory the interpreter could optimize the call to `exec` to `x=42`. The dynamic aspect comes in when you realize that the string passed to `exec` could be the result of user input: `name = input("Pick a variable name"); exec("{0}=42".format(name))`. Now, your program has a variable whose name is *completely* unknown until the program runs. This raises the question, "How would your code subsequently use such a variable?". (Answer: with difficulty.) – chepner Sep 19 '14 at 14:15