It was pointed out that locals ()
cannot be used normally in a function (it is even stated in the official documentation that it should not be used in the first place).
Be careful when using it.
I don't think there are many, but there are times when you want to set variable names dynamically, and sometimes you don't, so I tried to find out how to do that. (For example, if you want to read data from an external file and use the file name as a variable name?)
I found 2 (+ α) ways, so I would like to compare the speeds as an introduction.
rule
-Measure using the %% timeit
command on the Jupyter Notebook.
-Use 5 random lowercase letters as the variable name.
-Substitute a list containing integers from 0 to 9 as values.
-Measure the average of 1,000 loops.
** Preparation ** Prepare variable names in advance so as not to affect the measurement.
import random
chrs = [chr(i) for i in range(ord('a'), ord('z')+1)]
names = [''.join(random.sample(chrs, 10)) for i in range(10)]
The most common method.
%%timeit
for i in range(1000):
exec(f'{names[i]} = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]')
result
20.7 ms ± 75.7 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
locals ()
or globals ()
locals ()
and globals ()
are recognized as local variables and dictionaries that manage global variables, respectively (I'm sorry if they are different).
As with the normal dictionary type, you can use the indexer and .get ()
to get the value, and use .update ()
to update.
%%timeit
for i in range(1000):
locals().update({f'{names[i]}':[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]})
result
386 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Change the method a little
%%timeit
for i in range(1000):
locals()[names[i]] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
result
248 µs ± 387 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
ʻExec ()ratio, ・ ʻExec ()
: 1x
・ Locals (). update ()
: ** 53 times **
・ Locals () []
: *** 83 times ***
I was able to define it as quickly as possible.
** Conclusion **
Recommended Posts