Which more Pythonic - self.__class__ or type(self)?

avi.e.gross at gmail.com avi.e.gross at gmail.com
Thu Mar 2 19:35:41 EST 2023


My understanding is that python created functions like type() and len() as a
general purpose way to get information and ALSO set up a protocol that
classes can follow by creating dunder methods. I think the most pythonic
things is to avoid directly calling the dunder methods with a few exceptions
that mainly happen when you are building or extending classes. I mean some
dunder methods are then called directly to avoid getting into infinite loops
that would be triggered.

And note in many cases, the protocol is more complex. Is a length built-in?
If not, can the object be iterated and you count the results? Calling the
function len() may get you more info as it can leverage such things. And it
means you can sometimes leave out some methods and your code still works.

Be warned that type() is a very special function in python and when called
with more arguments, does many relatively beautiful but unrelated things. It
has a special role in the class or type hierarchy. But used with a single
argument, it harmlessly return a result you want.


-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com at python.org> On
Behalf Of Thomas Passin
Sent: Thursday, March 2, 2023 6:43 PM
To: python-list at python.org
Subject: Re: Which more Pythonic - self.__class__ or type(self)?

On 3/2/2023 5:53 PM, Greg Ewing via Python-list wrote:
> On 3/03/23 9:54 am, Ian Pilcher wrote:
>> I haven't found
>> anything that talks about which form is considered to be more Pythonic
>> in those situations where there's no functional difference.
> 
> In such cases I'd probably go for type(x), because it looks less
> ugly.
> 
> x.__class__ *might* be slightly more efficient, as it avoids a
> global lookup and a function call. But as always, measurement
> would be required to be sure.

Except that we don't know if "efficiency" - whatever that might mean 
here - matters at all.

-- 
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list