coding

Mikael Lövqvist

A use case for __new__ in python

by Mikael Lövqvist on

Background:

Sometimes in python you may need to make sure an instance is of the right class without having to check it every time.
One could write a function that would check some condition and either call the class to create a new instance or simply return the one that was already given as the argument. But then you need that function and, on top of that, the actual class definition and that gets a bit ugly in the namespace.

By using __new__ we can put that condition in there together with the code we would put in __init__ to get around having to call __init__ with the same arguments as __new__ was called.

Example:
Note that this example is written for python 3

Useful links:

Mikael Lövqvist

Text manipulation in python

by Mikael Lövqvist on

I am currently working on a project were I need to be able to handle text in a trivial way.
In order to do this I made a simple construct in python for this, you can have a look at the implementation here text_manipulation.py

Here follows an example of how this could be used:

variable T is first assigned indented_block to make things easier to type.
Then a program template is created where we have two markers, ¶includes and ¶main.
We also create a template for c functions named function.

In the example we replace ¶includes with a list of T("#include <file>") replacing file with the actual filenames. Then we define the body of the main function. We finally use the replace_kw function that will perform several replacements, one for each keyword argument.
Using the function template we can create out main function and also match indent level.

And here is the output of the program: