Conditional statements in a class, but outside of scope of the function
class, conditional-statements, python, scope
Solution
The class body is just Python code. It has specific scope rules, but anything goes otherwise. This means you can create functions conditionally:
class C:
if some_condition:
def optional_method(self):
pass
or pull methods from elsewhere:
import some_module
class D:
method_name = some_module.function_that_accepts_self
etc.
The Python documentation for `class` definitions states:
A class definition is an executable statement.
and
The class’s suite is then executed in a new execution frame (see section Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains only function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary.
Note the usually in that text. Essentially, the class body is executed as a function would, and anything you put in the body namespace becomes an attribute on the class.
The Naming and binding section then tells you:
The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods
so names you define in this block cannot be directly accessed in methods; you'd use `class.name` or `self.name` instead.
Problem
We know that with notation: ``` class Foo(object): a = 1 def __init__(self): self.b = 2 def c(self): print('c') ``` we can create static variable `Foo.a`, 'normal' variable `b`, which will be available after creating and instance of `Foo`, and method `c` Today I was really surprised, that I can use conditional statements in a class, but outside of scope of the function ``` class C(): if True: a = 1 b = 2 ``` Languages like C++/Java, taught me that legal notation is similar to: ``` class Name(): variable = <expression> ``` Could you describe other rules, which refer to this specific scope? How I should name this scope?