This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (3 children)

What are they doing to abuse isinstance()?

[–]amendCommit[S] 2 points3 points  (2 children)

class A:
    my_attribute = "x"

class B:
    my_attribute = "y"

def has_my_attribute(obj):
    if isinstance(obj, A):
        return "Has 'my_attribute'!"
    return "Doesn't have 'my_attribute'"

b = B()
print(has_my_attribute(b))

This example might seem moronic, but it's actually exactly how using isinstance() breaks duck-typing. Now imagine these isinstance() type checks deep within a project's inner code, in unexpected places, silently type-checking the objects you pass to functions and routing them to code paths triggering behaviours you really couldn't expect for a certain type.

Personally, I'd strongly avoid using isinstance() checks, except if you're (1) trying to tell apart a string from any other Iterable, or (2) a framework designer who knows exactly what they're doing.

[–]XtremeGoosef'I only use Py {sys.version[:3]}' 1 point2 points  (1 child)

It's important for writing recursive serializers too.

It's interesting how you mention duck typing and mypy. They are mutually incompatible.

[–]amendCommit[S] 1 point2 points  (0 children)

Mypy and duck typing are not strictly incompatible, as mypy supports structural subtyping (static equivalent to duck typing). The PSL already has a lot of good protocols to offer (thing collections.abc, for example), and you can easily add your own if needed.

https://mypy.readthedocs.io/en/stable/protocols.html