Look at this familiar code:

    class Foo(object):
        def __init__(self, a):
            self.a = a
        def bar(self, b):
            return self.a + b
    foo = Foo(1)

How do __init__ and bar get that self parameter?

Unbound methods

Well, bar is just a plain old function. (I'll just talk about bar for simplicity, but everything is also true for __init__, except for one minor detail I'll get to at the end.)

Foo.bar is a method, but it's an "unbound method"—that is, it's not bound to any particular Foo instance yet. As it turns out, these are exactly the same objects as plain old functions. (This wasn't true in Python 2.x, but I'll get to that later.)

You can call unbound methods just like any other function—but to do so, you have to pass an extra argument explicitly as self:
    >>> Foo.bar
    <function __main__.bar>
    >>> Foo.bar(foo, 2)
    3
You can even save them as plain old variables outside a class.
    >>> bar = Foo.bar
    >>> bar(foo, 2)
    3
This also means you monkeypatch a class to add new methods very easily:
    >>> def baz(self):
    ...     return self.a * 2
    >>> Foo.baz = baz
    >>> Foo.baz(foo)
    2
    >>> foo.baz()
    2
This even affects existing instances of the class (as long as they haven't shadowed the method with an instance variable by assigning to self.baz somewhere).

Bound methods

While Foo.bar is the same thing as bar, foo.bar is _not_ the same thing. It's a method, not a function:
    >>> foo.bar
    <bound method Foo.bar of <__main__.Foo object at 0x1066463d0>>
As you may be able to guess from the repr, a bound method wraps up a function and an object. And you can even pull them out:
    >>> foo.bar.__func__ is Foo.bar
    True
    >>> foo.bar.__self__ is foo
    True
This means that monkeypatching an instance is a bit more complicated, because you have to build a method. How do you do that?
Well, you could create a whole new class with the method, create an instance of that class, and copy the method from the new instance to the one you want to patch. But that's pretty ugly.

Think about how you construct other types. To make a Foo, you just call Foo(1). To make an int, you just call int('1'). The same goes for list, str, bytearray, and so on.

But what's the type of a method? Well, it's "method", but there's no built-in name bound to that.

For types that aren't normally useful, but occasionally are, Python hides the names, but gives us the types module to access them. So:
    >>> help(types.MethodType)
    Help on class method in module builtins:

    class method(object)
     | method(function, instance)
    …

    >>> foo.baz = types.MethodType(baz, foo)
    >>> foo.baz()
    2

How do bound methods work?

Any type can be callable, not just functions. You can define your own callable types just by defining a __call__ method. So, you can simulate a bound method pretty easily:
    class BoundMethod(object):
        def __init__(self, function, instance):
            self.__func__, self.__self__ = function, instance
        def __call__(self, *args, **kwargs):
            return self.__func__(self.__self__, *args, **kwargs)
Now you can use this exactly like the above:
    >>> foo.baz = BoundMethod(baz, foo)
    >>> foo.baz()
    2

How do bound methods get built?

Everything above, you could simulate yourself, without knowing anything deep about Python.

But there's one piece you can't. How is it that Foo.bar is an unbound method, but foo.bar is a bound method?

The obvious (and wrong) answer would be: When constructing a class instance, Python could create a bound method out of each unbound method and copy them in. That would be easy. But that wouldn't explain why adding Foo.bar made foo.bar work, even though foo had already been created.

In fact, you can look at the __dict__ for the objects and see that Python hasn't done this; the only thing that exists is the unbound method on Foo:
    >>> Foo.__dict__
    {'bar': <function Foo.bar at 0x1086259e0>, '__dict__': <attribute '__dict__' of 'Foo' objects>, …}
    >>> foo.__dict__
    {'a': 1, 'baz': <__main__.BoundMethod at 0x106646c10>}
The foo.baz that we created and added explicitly is there, but foo.bar isn't there. It's inherited from Foo.bar, just like any class attribute.

Except that normally, a class attribute doesn't magically change value or type when accessed from an instance:
    >>> class Spam(object):
    ...     eggs = 2
    >>> spam = Spam()
    >>> spam.eggs
    2
So, why is this different if the attribute is a function?

Descriptors

The secret is descriptors.

Descriptors have a reputation for being scary, deep magic. But once you understand what good they are, it's not too hard to understand why they work.

Every value in Python can have __get__, __set__, and __delete__ methods.

When you access a class attribute through an instance, if that the attribute has a __get__ method, it gets called with the instance and class, and whatever __get__ returns is what you see.

So, a function's __get__ method works like this:
    def __get__(self, instance, owner):
        return types.MethodType(self, instance)
And that's nearly all there is to it. I've cheated a little bit (e.g., the same __get__ has to work to return a bound method when accessed on an instance, a plain function when accessed directly on a class), but it's all pretty simple.

Putting it all together:

When you ask for foo.bar, Python looks in foo.__dict__, and doesn't find anything. So then it goes to foo's class and looks in Foo.__dict__, and finds something named "bar". Because "bar" was accessed through the class dictionary, Python calls Foo.bar.__get__(foo, Foo), which returns a bound method.

A classmethod is just a function whose __get__ returns types.MethodType(self, cls), which means you end up with a bound method bound to the class, rather than an instance. And a staticmethod is just a function whose __get__ returns itself. A property is just an attribute whose __get__, __set__, and __delete__ methods call the functions you defined in your @property. And so on. When you look behind the curtain, the wizard isn't that scary at all.

You can read more about descriptors in the Descriptor HowTo Guide.

History

You may have noticed that we have actual types for functions and bound methods, but unbound methods are just the same thing as functions. Why even have a name for something if it's just a confusing synonym of something everyone understands?

You may have also noticed that __get__ takes an owner parameter that nobody uses.

In Python 2.x, unbound methods were a different type from functions, and very closely related to bound methods.

A Python 3 bound method has attributes __func__ and __self__. In Python 2, these were called im_func and im_self, and there was a third called im_class. A method with None for im_self was an unbound method; otherwise, it was a bound method. You should be able to imagine how functions and @classmethods and @staticmethods implemented __get__.

As it turns out, unbound methods don't add much. They make calls a little slower, make it as hard to monkeypatch classes (which is relatively common) as instances (which is uncommon), and add a whole new concept that you need to understand the complexities of. What do you get in exchange? Basically, just the fact that they can tell you which class they're part of. But really, the only thing you want to do with that is display it—which __qualname__ does a much better job at—or try to use it for pickling—which doesn't work anyway.

Python 2.x also has some wrinkles dealing with classic classes, but these only come up in three cases:
  • Ancient code written to be compatible with Python 1.5-2.1.
  • Simple bugs by novices who don't know how to write a new-style class.
  • Troll code by people who insist that they prefer classic classes just because the core devs and everyone else in the Python community disagrees.
If you want to know the details, read New-style and classic classes.

What was that about __init__?

I was hoping you'd forget…

Python reserves the right to treat special methods specially.

What's a special method? This isn't actually quite defined anywhere. But basically, it's any method whose name begins and ends with double underscores, and whose purpose is to be called by the language itself or by some builtin code. (Note that most implementations provide a way for extension modules to add new builtin code—that's what the C API, the Jython bridge, etc. are all about.)

How are they treated specially? Basically, for some special methods, in some cases, Python ignores __getattr__, __getattribute__ and any other attribute mechanism besides __dict__, and skips the instance __dict__ to go straight to the class and its base classes.

For different implementations, and even different versions of the same implementation, the set of methods and cases and the exact details of the specialness differ. If you want to know about CPython does, look at the source to _PyObject_LookupSpecial, and grep for calls to it in the Python, Objects, and Modules directories.

Anyway, in CPython 3.3, when calling __init__ as part of object construction when you haven't overridden __new__, you go through _PyObject_LookupSpecial; in other cases, it's a normal lookup.

Of course it kind of makes sense for __init__. Normally, an instance's dict is empty until the __init__ method, and methods like __getattr__ often need setup that's done in __init__ to work.
3

View comments

It's been more than a decade since Typical Programmer Greg Jorgensen taught the word about Abject-Oriented Programming.

Much of what he said still applies, but other things have changed. Languages in the Abject-Oriented space have been borrowing ideas from another paradigm entirely—and then everyone realized that languages like Python, Ruby, and JavaScript had been doing it for years and just hadn't noticed (because these languages do not require you to declare what you're doing, or even to know what you're doing). Meanwhile, new hybrid languages borrow freely from both paradigms.

This other paradigm—which is actually older, but was largely constrained to university basements until recent years—is called Functional Addiction.

A Functional Addict is someone who regularly gets higher-order—sometimes they may even exhibit dependent types—but still manages to retain a job.

Retaining a job is of course the goal of all programming. This is why some of these new hybrid languages, like Rust, check all borrowing, from both paradigms, so extensively that you can make regular progress for months without ever successfully compiling your code, and your managers will appreciate that progress. After all, once it does compile, it will definitely work.

Closures

It's long been known that Closures are dual to Encapsulation.

As Abject-Oriented Programming explained, Encapsulation involves making all of your variables public, and ideally global, to let the rest of the code decide what should and shouldn't be private.

Closures, by contrast, are a way of referring to variables from outer scopes. And there is no scope more outer than global.

Immutability

One of the reasons Functional Addiction has become popular in recent years is that to truly take advantage of multi-core systems, you need immutable data, sometimes also called persistent data.

Instead of mutating a function to fix a bug, you should always make a new copy of that function. For example:

function getCustName(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

When you discover that you actually wanted fields 2 and 3 rather than 1 and 2, it might be tempting to mutate the state of this function. But doing so is dangerous. The right answer is to make a copy, and then try to remember to use the copy instead of the original:

function getCustName(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

function getCustName2(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[2] + ' ' + custRec[3];
    return fullname;
}

This means anyone still using the original function can continue to reference the old code, but as soon as it's no longer needed, it will be automatically garbage collected. (Automatic garbage collection isn't free, but it can be outsourced cheaply.)

Higher-Order Functions

In traditional Abject-Oriented Programming, you are required to give each function a name. But over time, the name of the function may drift away from what it actually does, making it as misleading as comments. Experience has shown that people will only keep once copy of their information up to date, and the CHANGES.TXT file is the right place for that.

Higher-Order Functions can solve this problem:

function []Functions = [
    lambda(custID) {
        custRec = readFromDB("customer", custID);
        fullname = custRec[1] + ' ' + custRec[2];
        return fullname;
    },
    lambda(custID) {
        custRec = readFromDB("customer", custID);
        fullname = custRec[2] + ' ' + custRec[3];
        return fullname;
    },
]

Now you can refer to this functions by order, so there's no need for names.

Parametric Polymorphism

Traditional languages offer Abject-Oriented Polymorphism and Ad-Hoc Polymorphism (also known as Overloading), but better languages also offer Parametric Polymorphism.

The key to Parametric Polymorphism is that the type of the output can be determined from the type of the inputs via Algebra. For example:

function getCustData(custId, x)
{
    if (x == int(x)) {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return int(fullname);
    } else if (x.real == 0) {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return double(fullname);
    } else {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return complex(fullname);
    }
}

Notice that we've called the variable x. This is how you know you're using Algebraic Data Types. The names y, z, and sometimes w are also Algebraic.

Type Inference

Languages that enable Functional Addiction often feature Type Inference. This means that the compiler can infer your typing without you having to be explicit:


function getCustName(custID)
{
    // WARNING: Make sure the DB is locked here or
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

We didn't specify what will happen if the DB is not locked. And that's fine, because the compiler will figure it out and insert code that corrupts the data, without us needing to tell it to!

By contrast, most Abject-Oriented languages are either nominally typed—meaning that you give names to all of your types instead of meanings—or dynamically typed—meaning that your variables are all unique individuals that can accomplish anything if they try.

Memoization

Memoization means caching the results of a function call:

function getCustName(custID)
{
    if (custID == 3) { return "John Smith"; }
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

Non-Strictness

Non-Strictness is often confused with Laziness, but in fact Laziness is just one kind of Non-Strictness. Here's an example that compares two different forms of Non-Strictness:

/****************************************
*
* TO DO:
*
* get tax rate for the customer state
* eventually from some table
*
****************************************/
// function lazyTaxRate(custId) {}

function callByNameTextRate(custId)
{
    /****************************************
    *
    * TO DO:
    *
    * get tax rate for the customer state
    * eventually from some table
    *
    ****************************************/
}

Both are Non-Strict, but the second one forces the compiler to actually compile the function just so we can Call it By Name. This causes code bloat. The Lazy version will be smaller and faster. Plus, Lazy programming allows us to create infinite recursion without making the program hang:

/****************************************
*
* TO DO:
*
* get tax rate for the customer state
* eventually from some table
*
****************************************/
// function lazyTaxRateRecursive(custId) { lazyTaxRateRecursive(custId); }

Laziness is often combined with Memoization:

function getCustName(custID)
{
    // if (custID == 3) { return "John Smith"; }
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

Outside the world of Functional Addicts, this same technique is often called Test-Driven Development. If enough tests can be embedded in the code to achieve 100% coverage, or at least a decent amount, your code is guaranteed to be safe. But because the tests are not compiled and executed in the normal run, or indeed ever, they don't affect performance or correctness.

Conclusion

Many people claim that the days of Abject-Oriented Programming are over. But this is pure hype. Functional Addiction and Abject Orientation are not actually at odds with each other, but instead complement each other.
5

View comments

Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.