Sitemap

Replicating Javascript ‘Bind’ in Python

Exploring Advanced Python Concepts

--

If you aren’t familiar with Javascript’s bind function, it works like this:

bind in javascript

In this example, we can see that bind sets an argument to a function. You can think of it as hard coding any number of arguments to a function. In essence, it changes the add function like this:

add(a, b) → add(3, b)

We bind 3 to the add function.

Why replicate this in Python?

In this article you will see advanced Python concepts that showcase the flexibility and power of Python.

Is it necessary to write this library? Nope, not at all — in fact 9/10 programmers believe that doing so is horribly unnecessary and confusing.

However it is incredibly fun to solve challenging problems and the act of doing so can teach us more about Python. If you’ve ever wondered about higher order functions, decorators, metaclasses, and inheritance, we’ll explore these concepts and more.

Advanced Python knowledge is required for this tutorial.

Tested on Python 3.5 and 3.6.

Before we get started, I recommend cloning the repository and running the examples as we go along.

git clone https://github.com/jamesaud/pybind

The code is available at:

*I use PyCharm to ensure the module/imports work properly. If you run into import errors, an easy fix is move the examples up 1 folder.

Part 1: Binding a Function

This code won’t run without errors yet, but we’ve written down where we want to end up. That’s a good starting point!

This is an interesting piece of code. We are taking a function as the first argument, and passing default arguments for the *args and **kwargs.

We return an inner function that calls the original function with the default parameters. It also accepts new parameters, *a and **kw.

Let’s make this look more like the javascript code. In Python, functions are first class objects so we can add methods to them:

That’s pretty awesome! We set .bind as a method to the add function.

It’s fairly ungraceful to pass a function to bindable though. Notice, bindable is passed a function as it’s first parameter; this means we can use bindable as a decorator:

If you take a look at bind and bindable, they are practically the same function!

bindable is the bind function with a default parameter for fn. Wait a minute… we have a function that let’s us assign default parameters: bind!

This works the exact same as the previous bindable function. The function fn is bound to the bind function. It’s pretty cool that we wrote a function bind that can be called on itself!

One last thing. If we print out our function, the original doc string is messed up.

In essence, the inner function is basically our original function fn, and we want the documentation to stay the same. So we decorate it with wraps:

Let’s look at another way of doing this, for the sake of fun and learning:

You can write decorators as classes. This can be useful for organization, and for holding state.

The add function is passed to __init__ by the decorator, and __call__ is invoked with the parentheses.

You could even add callback functionality like this:

This code can be found at: https://github.com/jamesaud/pybind/blob/master/bind_functions.py

And examples: https://github.com/jamesaud/pybind/blob/master/examples/functions.py

Part 2: Binding Instances

Falling deeper down the rabbit hole

Let’s say we have a class Dog.

We might want to be able to call bind on any method of a Dog object like this:

Our implementation of bind doesn’t work for instances objects, because objects need to keep maintain their state — the bound function needs to exist on the object.

To sum up what needs to be done:

  • Class methods should have a function bind that can be called
  • bind calls the original function with given parameters

Here’s a method that takes an object, a method name, and parameters. It binds the parameters to the object’s method.

getattr: gets the method from an object, given a method name
setattr: updates the method, replacing it with the bind version

Get James Audretsch’s stories in your inbox

Join Medium for free to get updates from this writer.

Here’s a helper function to get the user defined methods. Replacing Python’s built-in methods turned out being messy and not that useful:

Python built-ins looks like __init__, __len__, __lt__, etc. We don’t want to bind these, and run into some trouble if we try to.

Callable returns True only if the attribute is a function.

We need a function that will add a bind function to our original methods:

What the heck is going on here? Let’s look at it in steps:

  1. bind with no parameters literally just is a lambda around our function. This way we don’t end up altering the original function.
  2. method.__dict__[‘bind’]: let’s us add a function named bind to the method bind(bind_instance_method, obj, method_name): binds parameters to the original method

The original attributes don’t actually exist on the object’s __dict__. They exist on object.__class__.__dict__:

adding to the method.__dict__ is a hack that lets us avoid overwriting the original.

Now we can actually call bind_instance_methods on an object directly:

We want to use the method as a decorator though:

Replace the class’ init function with one that calls bind_instance_methods first, then calls the original init function.

Our original example now works:

Code is available here: https://github.com/jamesaud/pybind/blob/master/bind_instance.py

And examples: https://github.com/jamesaud/pybind/blob/master/examples/instances.py

Part 3: Binding Classes

To bind or not to bind; that is the question

It would be nice to have a way to bind classes, so that the objects that are instantiated have bound attributes:

Binding a class sets default parameters for all objects created from that class. Calling Dog.bind allows us to bind parameters to the Dog’s __init__ function.

Essentially it relies on subclassing the original class, which you can dynamically do in Python:

This creates a new class inheriting from the old one.

This also relies on passing self in the correct order to the __init__ method:

Whenever an object calls a method, it is passed as the first argument as self. So we need to bind all of the other arguments in the right order — and then when the method is actually called from the object, pass self.

This final piece of code allows us to bind a class’ __init__ method:

With these methods, we can write code like:

It would also be nice to be able to bind other methods of a class as well, not just the __init__ function. You would normally subclass and override the method to change the behavior. Let’s try to make the following work:

It is as if we have a copy of the class, with default parameters set for a specific method.

I’ll let you try to piece through the rest of the code that enables this functionality if you’d like — but be warned, it isn’t trivial:

Now the following code will work:

Code: https://github.com/jamesaud/pybind/blob/master/bind_class.py

Examples: https://github.com/jamesaud/pybind/blob/master/examples/classes.py

3. Bindable Classes and Subclasses

Let’s get Meta

The only problem is that if you subclass Dog, you can’t bind methods anymore. This is an interesting problem that can be solved metaclasses.

An implementation of Bindable Instance Methods and Bindable Class Methods are shown. In fact, you can have BindableMeta inherit from both!

Meta-classes allow you to control class generation, similar to how classes allow you to control object generation. In the __init__ function, we can take the class and apply our decorator to it to enable the bind functionality. The cool thing about meta-classes is that they apply to the inherited classes as well.

This is shown in the following example:

Code: https://github.com/jamesaud/pybind/blob/master/MetaBind.py

Examples: https://github.com/jamesaud/pybind/blob/master/examples/meta_classes.py

I hope you enjoyed this ‘tutorial’.

I had a lot of fun and spent countless hours puzzling over how to implement the desired behavior.

If you think of a cool problem like this, it’s well worth endeavoring in pursuing it! I feel like I learned an incredible amount in the process of coding this up. Even if you fail, like I did many times, learning from your failures and iteratively improving is what makes you a better programmer :) Start with small, easier to solve pieces; as you put them together you may find yourself stumbling upon a remarkable solution!

Feel free to ask questions in the comments.

--

--