Plasmapy: Use ABCs from numbers to type check integers & real numbers

Created on 20 Jul 2018  路  3Comments  路  Source: PlasmaPy/PlasmaPy

Up until recently, I've been writing code like this:

def return_integer(n):
    if not isinstance(n, int):
        raise TypeError
    return n

This is all well and good...until we try to pass in a numpy.int object and get a TypeError. Grumblemuffins!

However, abstract base classes to the rescue! We can instead do things like:

import numbers
def return_integer(n):
    if not isinstance(n, numbers.Integral):
        raise TypeError
    return n

This function now works for numpy.int objects as if by magic! Similarly, we can use numbers.Number, numbers.Complex, and numbers.Real instead of checking for, e.g., a float or complex object.

However, I've included code like the first example above in quite a few places, including in atomic and mathematics, and this is likely to have come up in a bunch of other places as well. We should update these type checks so that we use isinstance(n, numbers.Integral) and isinstance(r, numbers.Real) instead of isinstance(n, int) and isinstance(r, float).

I've also used int instead of numbers.Integral in type hint annotations as well. However, this isn't necessarily as bad since type hints are not automatically used for type checks. That said, if we want to use mypy, we would probably want to update the type hint annotations too.

Bug Good first contribution high

Most helpful comment

I'd like to take on this issue if it's still available.

All 3 comments

One more thing we should do:

  • [ ] Include this information in the development guide in our docs.

I'd like to take on this issue if it's still available.

Sure, go for it!

Was this page helpful?
0 / 5 - 0 ratings