local-variables

Using locals() and format() method for strings: are there any caveats?

Using locals() and format() method for strings: are there any caveats? Question: Are there any disadvantages, caveats or bad practice warnings about using the following pattern? def buildString(user, name = ‘john’, age=22): userId = user.getUserId() return “Name: {name}, age: {age}, userid:{userId}”.format(**locals()) I had a very repetitive string generation code to write and was tempted to …

Total answers: 3

What's the scope of a variable initialized in an if statement?

What's the scope of a variable initialized in an if statement? Question: This could be a simple scoping question. The following code in a Python file (module) is confusing me slightly: if __name__ == ‘__main__’: x = 1 print x In other languages I’ve worked in, this code would throw an exception, as the x …

Total answers: 7

How to get local variables updated, when using the `exec` call?

How to get local variables updated, when using the `exec` call? Question: I thought this would print 3, but it prints 1: # Python3 def f(): a = 1 exec("a = 3") print(a) f() # 1 Expected 3 Asked By: ubershmekel || Source Answers: This issue is somewhat discussed in the Python3 bug list. Ultimately, …

Total answers: 3