The Python Oracle

How can one create new scopes in python

This video explains
How can one create new scopes in python

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Question
00:39 Accepted answer (Score 6)
01:37 Answer 2 (Score 8)
01:57 Answer 3 (Score 6)
02:25 Answer 4 (Score 6)
02:53 Thank you

--

Full question
https://stackoverflow.com/questions/5419...

Question links:
[this]: https://stackoverflow.com/questions/5417...
[if True:]: https://stackoverflow.com/questions/5417...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #scope

#avk47



ACCEPTED ANSWER

Score 7


In Python, scoping is of three types : global, local and class. You can create specialized 'scope' dictionaries to pass to exec / eval(). In addition you can use nested scopes (defining a function within another). I found these to be sufficient in all my code.

As Douglas Leeder said already, the main reason to use it in other languages is variable scoping and that doesn't really happen in Python. In addition, Python is the most readable language I have ever used. It would go against the grain of readability to do something like if-true tricks (Which you say you want to avoid). In that case, I think the best bet is to refactor your code into multiple functions, or use a single scope. I think that the available scopes in Python are sufficient to cover every eventuality, so local scoping shouldn't really be necessary.




ANSWER 2

Score 7


If you just want to create temp variables and let them be garbage collected right after using them, you can use

del varname

when you don't want them anymore.

If its just for aesthetics, you could use comments or extra newlines, no extra indentation, though.




ANSWER 3

Score 6


Why do you want to create new scopes in python anyway?

The normal reason for doing it in other languages is variable scoping, but that doesn't happen in python.

if True:
    a = 10

print a



ANSWER 4

Score 6


Python has exactly two scopes, local and global. Variables that are used in a function are in local scope no matter what indentation level they were created at. Calling a nested function will have the effect that you're looking for.

def foo():
  a = 1

  def bar():
    b = 2
    print a, b #will print "1 2"

  bar()

Still like everyone else, I have to ask you why you want to create a limited scope inside a function.