Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That might seem nice for your limited example, but it breaks down when you realize that in example #3 there would be no easy way to differentiate between scopes.

  y = 100
  x = 15
  
  class MyClass(object):
    x = 50
    def __init__(self, x):
      self.x = x

    def length():
      return x * y
What does that mean? Does MyClass(10).length() raise an AttributeError because MyClass doesn't have an attribute named y? Does it automatically recognize there's a y in the outer scope and use that, or does it call __getattr__ first (i.e. method that gets called when a missing attribute is accessed)? Furthermore, how do I specify that I want to access the class attribute x, or that I want to access the nonlocal x?


In my opinion, there are far bigger problems with pythons scoping. Why is for/if/etc not it's own scope? You can define a temporary variable in there and mistakenly use it somewhere down the line. In a "for i in ..", the i should be cleared after the loop but it isn't. Why can't you create a new scope within a function? This allows you to bundle related stuff together and be sure the scope is cleared afterwards, so as to not mistakenly reuse variables. The thing that you're promoting as an advantage of explicit self is already broken by having a single scope for the whole function.

Blocks like this are an imensely useful way to keep scopes clean:

   int someMethod(){
   	...
   
   	{ // some small stuff that doesn't warrant a new method but you don't want it to bleed into the remaining part of the function, e.g.:
   		float x = readNextFloat();
   		float y = readNextFloat();
   		float z = readNextFloat();
   		float length = sqrt(x*x + y*y + z*z);
   		cout << length;
   	}
   	
   	// do some other things without worrying about potentially initialized variables
   	...
   }




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: