Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if __str__ is implemented by an object

Tags:

python

I want to dynamically implement __str__ method on a object if the object doesn't already implement it.

I try using hasattr(obj, '__str__') it always returns me true as it picks it up from object class.

Is there a way to determine if an object actually implements __str__ ?

I know I can use inspect.getmembers(obj) but I am searching for a more pythonic way

EDIT

class Employee(object):
def __init__(self, name, age, emp_code):
    self.name = name
    self.age  = age
    self.emp_code = emp_code

Test

e = Employee("A", 23, "E1")
print hasattr(e, '__str__')
>> True

I want a check that returns False instead of picking up the method inherited from object.

like image 728
Bhushan Avatar asked Oct 28 '13 06:10

Bhushan


1 Answers

Since what you want to check is if it has a __str__ implementation that is not the default object.__str__. Therefore, you can do this:

Foo.__str__ is not object.__str__

To check with instantiated objects you need to check on the class:

type(f).__str__ is not object.__str__

This will also work even if Foo doesn't implement __str__ directly, but inherited it from another class than object, which seems to be what you want.

like image 188
Lennart Regebro Avatar answered Sep 22 '22 08:09

Lennart Regebro