Using Python 3.9 features in Python 3.8 — writing a polyfill

Explaining how to extend the built-in classes

Fullstack CTO
4 min readJun 13, 2020

In Python 3.9 a new feature is announced: a new merge syntax for two or more dictionaries. If we used to write:

It’s kind of cool, wow. But if you think about it, there’s no rocket scientist here. What’s more, you can use this syntax today by making your own polyfill and start using this syntax right now in Python 3.8

How? Let’s figure it out.

Operator overloading

Python has a cool feature — operator overloading, which can do wonders with the language and create your own DSL. How do you actually implement the behavior for the above features? We take the code from Python itself:

Writing your own version of the Python39Dict dictionary

Great! Everything works, we got it on the way out:

{‘f1’: 123, ‘f2’: ‘abc’, ‘b1’: 456, ‘b2’: ‘def’}
{‘f1’: 123, ‘f2’: ‘abc’, ‘b1’: 456, ‘b2’: ‘def’}

But it’s a bit uncomfortable to write Python39Dict({}) every time, isn’t it? Can we add these methods to an existing dictionary class?

How do we add a method to an existing class?

Let’s start with the basic stuff, add a method to an existing class:

Okay, so we know how to add methods to existing classes. Great, let’s try it:

Hmm, what to do?

Builtins

We find that there is a built-in builtins module. It allows you to modify built-in objects.

Already better, but there’s a but! We have to explicitly specify when creating that we use the dictionary and have to write the word dict. Can we improve this too? To make the dictionaries look native?

Forbiddenfruit

Yes, forbidden fruit is sweet and should not be touched and abused, but if you really need to…

Install the forbiddenfruit module and write the following code:

Wow wow! It works! We make it as a module, put the code into the python39dict file, and now we can plug the new dictionary fusion syntax into the project:

That’s it. As you can see, you can try to extend the language even if it doesn’t have some ready-made features and even offer some features to the community, which may end up in the spec and in the language. Of course object fusion in Python 3.9 will be implemented at the language level in C code, not through Python, and will work clearly faster and safer. But you can try to add new features like this as long as you wait for the new version of the language to come out.

Each of your likes is a motivation for me to keep writing articles and telling you interesting things from the programming world. If this article was helpful, please click the button :)

Like, was it useful ?

--

--

Fullstack CTO
Fullstack CTO

Written by Fullstack CTO

CTO and co-founder at NEWHR & Geekjob

No responses yet