Search code examples
pythonmonkeypatchingshadowingbuilt-in

Overriding len in __init__.py - python


I would like to assign an another function to len in __init__.py file of my package the following way:

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

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


Solution

  • When you try to load a name that is not defined as a module-level global or a function local, Python looks it up in the __builtin__(builtins in Python 3) module. In both versions of Python, this module is also availabe as __builtins__ in the global scope. You can modify this module and this will affect not only your code but any python code anywhere that runs after your code runs!!

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