0

In Python, I want to prevent my local variable to be hoisted to the parent scope. Basically, I want to avoid accidental programming errors by keeping the variable b's scope local to the 'if' block. Is it possible in Python. How?

a = 10
if a == 10:
    b = 5
else:
    c = 0

print b
# prints 5
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Raunak
  • 3,314
  • 1
  • 22
  • 28
  • 2
    There is no variable hoisting going on. The `if` block does not create a scope. Everything in your code is in the global scope. – juanpa.arrivillaga Apr 01 '19 at 06:13
  • Ok, to clarify my question further: Is it possible by any means (knowing the default scoping rules in Python) to limit the visibility of variable 'b' to the immediate containing block. – Raunak Apr 01 '19 at 06:33
  • 1
    No, python does not have block scope. You could borrow a common JavaScript idiom which is to create and immediately invoke a function – juanpa.arrivillaga Apr 01 '19 at 06:44

0 Answers0