A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2002-March/022014.html below:

[Python-Dev] Evil isinstance()

[Python-Dev] Evil isinstance()Alex Martelli aleax@aleax.it
Sun, 31 Mar 2002 20:43:48 +0100
On Saturday 31 March 2002 9:45, Aahz wrote:

"""
The problem is that in some cases the __init__ for a class needs to
dispatch based on the type of the operand.  For example, int() takes
both numbers and strings.  What should we recommend as "standard
practice" for this issue if isinstance() is disrecommended?
"""

What I recommend, FWIW, until and unless PEP 246 eventuates
and makes the world wonderful:

# if there's a specifically relevant special-method, such as __int__ is for
# int(), you can of course first try getting thearg.__int__ -- if that
# fails, or if nothing that relevant applies, you can then proceed with
# something along the lines of:

try: thearg+''
except TypeError: pass
else:
    "do the stringlike case here"

try: thearg+0
except TypeError: pass
else:
    "do the numberlike case here"

Why would you want your function to break if called with an instance
of UserString, say, or a user-defined number type?  Smooth polymorphism
is high on the list of Python's strong points -- why break it, when you can
preserve this excellent quality?


Alex



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4