types - How can I check if my python object is a number? -


this question has answer here:

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

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -