Python weirdness: can anyone explain to this Python newbee?

I’m not quite sure what you mean by the inability to define a function in another function, that works perfectly fine:

def make_adder(x):
    def adder(y):
        return x + y
    return adder

adds_three = make_adder(3)
print(adds_three(2))  # 5

In this case, the nested function forms a “closure” over any variables it references from the parent, so it still retains access. In a class setting, that would include self if you needed to, you’d perfectly well be able to assign it to an instance value to get something that behaves as a method.

The way Python does methods is fairly elegant also, it’s not as restrictive as you think and allows other things too. What happens is that attributes defined on the class but accessed from the instance can define “descriptor” methods which decide what happens. For functions, these are what create the bound method objects discussed earlier, and are how @property works.

Unrelated side note - RuntimeError is normally only raised to indicate something went terribly wrong inside the interpreter, it’s not something Python code would usually raise. It’s probably better to use ValueError or maybe TypeError here.

Thanks again Spencer - you are helping me become more pythonic!

I understood that you can define functions in nested contexts including within other function definitions. Essentially my complaint is that not all functions work like lambdas. Lambdas are fully first class, but not fully functions! In my Lua addled brain a function definition should be syntactically a literal, so it always creates a nameless function object which you can then bind to a name (or not). You can embed a full function definition as a parameter in a function call (as well as in a function definition) and also in the constructor of a tuple or any other object. Python’s sensitivity to indentation presents some lexical challenges with this, but I am sure cleverer people than me could work them out!

As for the closure mechanism, that is the same as Lua and meets with my approval! But why do they not use this mechanism for ‘bound method’ objects? As I mentioned before, 99% of the time you are referencing the method through ‘self’ so you do not need the closure. Would it not be better to leave it up to the programmer to explicitly create closures in the minority case were they wish to use the reference in contexts were they do not have access to ‘self’?