Overriding len in __init__.py - python

I would like to assign another function to len in the __init__.py file of my package as follows:

 llen = len len = lambda x: llen(x) - 1 

It works fine, but only in the __init__.py file. How can I affect other modules in my package?

+8
python builtin monkeypatching shadowing
source share
2 answers

When trying to load a name that is not defined as a global module level or local function, Python looks for it in the __builtin__ module ( builtins in Python 3). In both versions of Python, this module is also available as __builtins__ in the global scope. You can change this module, and this will affect not only your code, but also any Python code anywhere that will be launched after your code is run!

 import __builtin__ as builtins # import builtins in python 3 llen = len builtins.len = lambda a:llen(a) - 1 
+2
source share

It may not be the answer you are looking for, but I would not do it if I were you (and I’m sure that you cannot easily, anyway).

The reason you shouldn't be because python uses len objects internally on it to perform certain operations. Another reason is pure logic. Your len function, defined above, will return a negative length for empty lists or empty things. This seems very unpleasant to me.

What you can do is override the length method only for certain classes (this can make a lot of sense to you). You can use operator overloading for this, just override the __len__ method in your class:

 class MyList(object): def __len__(self,): # Do your thing 

You can also view metaclasses, there is a very good stack overflow question on this.

+4
source share

All Articles