modify class loose type evaluation

Viewed 36

Trying to add a method to a native class, the type of this class seems to be différent in a type() event keeping the same repr presentation

>>> type([]) == list
True
>>> type([])
<class 'list'>
>>> class list(list) :
...    def dummy( self) :
...       self.append( "Something")
... 
>>> type( []) == list
False
>>> type([])
<class 'list'>

Goal is to add the method to a type (list in this sample but it was dict at first attempt with more complex method) but this new behavior is not wanted. So best will be to implement the new method on a more correct way, not having a workaround for type of.

from some reply below (but not adding method to native, just create a sub class with same name in current workspace)

>>> x=list([])
>>> type(x) == list
True
1 Answers
print(list) # <class 'list'>

class list(list):
    def dummy(self):
        self.append( "Something")

print(list) # <class '__main__.list'>

In this example list is referenced as the standard lib list until a class in main gets defined with the same name. From then on the program references this class instead of the other.

I don't think you can change native python classes. You would have to change the standard library code for that...

Related