types - How can I check if my python object is a number? -
this question has answer here:
- python: pythonic way check if object number 10 answers
in java numeric types descend number use
(x instanceof number).
what python equivalent?
in more recent python versions (2.6+; in older versions you're pretty limited checking few hardcoded types), correct way test if variable instance of numbers.number
:
>>> import numbers >>> import decimal >>> [isinstance(x, numbers.number) x in (0, 0.0, 0j, decimal.decimal(0))] [true, true, true, true]
this uses abcs , work build-in number-like classes, , third-party classes if worth salt (registered subclasses of number
abc). however, in many cases shouldn't worry checking typed manually - python duck-typed , mixing compatible types works, yet barf error message when operation doesn't make sense (4 - "1"
), manually checking needed. it's bonus, can add when finishing module avoid pestering others implementation details.
Comments
Post a Comment