Defining a variable from a string

I am trying to define a variable inside a function. vars () shows that the variable is created, but gives me NameError: exception. What am I doing wrong?

def a(str1): vars() [str1] = 1 print vars() print b a('b') 

exit:

 {'str1': 'b', 'b': 1} 

an exception:

 NameError: global name 'b' is not defined 
+4
source share
3 answers

Your code works for me. Perhaps you should try an alternative approach:

 exec(str1 + '=1') 

This will do b=1

+2
source

You invoke undefined behavior. From the vars() documentation :

Note The returned dictionary must not be changed: the effects in the corresponding symbol table are undefined.

Other answers give possible solutions.

+4
source

If you do not understand why the design does not work, not the next person who should read your code. If you mean

 b = 1 

you have to say it. In this case, vars() gives you access to the local dictionary of the function, so your code is equivalent

 def a(): b = 1 

where b is local to a and evaporates when it goes out of scope after exiting a .

premature optimization is the root of many people trying to invade Python

 from itertools import izip import timeit import msw.wordlist def zip_list(p): """construct a dictionary of length 100 from a list of strings""" return dict(zip(p[:100], p[100:])) def izip_list(p): """as zip_list but avoids creating a new list to feed to dict()""" return dict(izip(p[:100], p[100:])) def pass_list(p): """take 100 elements of a list and do nothing""" for i in p[:100]: pass def exec_pass_list(p): """exec() a no-op 100 times""" for i in xrange(100): exec('pass') # returns a list of 64'000 unique lowercase dictionary words for tests words = msw.wordlist.Wordlist() words.shuffle() words = words[:200] print 'words', words[:5], '...' for func in ['zip_list', 'izip_list', 'pass_list', 'exec_pass_list']: t = timeit.Timer('%s(words)' % func, 'from __main__ import words, %s' % func) print func, t.repeat(number=10**5) 

which gives:

 words ['concatenated', 'predicament', 'shtick', 'imagine', 'stationing'] ... zip_list [1.8603439331054688, 1.8597819805145264, 1.8571949005126953] izip_list [1.5500969886779785, 1.5501470565795898, 1.5536530017852783] pass_list [0.26778006553649902, 0.26837801933288574, 0.26767921447753906] exec_pass_list [74.459679126739502, 75.221366882324219, 77.538936853408813] 

I did not try to implement everything that the OP tried to do, because it is 50 times slower, so as not to create word sorting, making further testing kind of stupid.

+1
source

Source: https://habr.com/ru/post/1315821/


All Articles