Jul-09-2018, 11:17 PM
(Jul-09-2018, 11:00 PM)Windspar Wrote: If you know the type. You should be able to detect it.If all the OP wants is to type-check, that may be fine. It depends on the definition of "number". If that definition is the set of types you describe, that works.
I think a big part of why Python tends to use duck typing by convention is this - a more flexible definition of "number" isn't its OOP is-a relationship with a set of classes (or types), rather, it's a set of operations available on an object. Defining the types in advance precludes new user types that support all the operations, unless they inherit from something. Even that aside, sometimes a third-party library comes along which you might want compatibility with, so the user doesn't even have the option of extending that class. It is for this reason that I strongly recommend against type-checking, unless it's really the only option.
On a potentially ironic note... if you're serious about the actual types (especially if we're talking about objects), I recommend you check out type hinting. It can help catch these issues before you run your script, instead of during. Why might this be ironic? Python's type hinting doesn't support duck typing (Scala, as a comparison, offers "structural typing" which is basically static duck-typing; it is not widely used and has performance issues but it's a proof-of-concept). I look forward to the day when Python does support type hints for duck typing, but it's not today :)