Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 763
DorianOlympia Avatar asked Nov 01 '15 14:11

DorianOlympia


2 Answers

This may not be the answer you're looking for, but I wouldn't do this if I were you (and I'm pretty sure you can't easily, anyway).

The reason why you shouldn't is that python uses len internally on it's objects to perform certain operations. Another reason is pure broken logic. Your len function defined above would return a negative length for empty lists, or empty things. This seems quite broken to me.

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

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

You may also want to look into meta classes, there is a very good stack overflow question on this subject.

like image 93
nichochar Avatar answered Sep 19 '22 03:09

nichochar


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
like image 23
pppery Avatar answered Sep 20 '22 03:09

pppery