Search code examples
pythonpython-3.xisinstancegmpy

How to check if a variable is an instance of mpfr in Python 3?


I want to know how to check whether a variable is of type mpfr or not, this might sound trivial but a simple isinstance(v, mpfr) can't do the trick.

Example: create a variable that is an instance of mpfr, how to verify said variable is an instance of mpfr?

import gmpy2
from gmpy2 import mpfr

f = mpfr('0.5')

The most intuitive way fails:

>>> isinstance(TAU, mpfr)
TypeError: isinstance() arg 2 must be a type or tuple of types

Because mpfr is a function:

>>> mpfr
<function gmpy2.mpfr>

gmpy2 only has one attribute named mpfr, and it is the above function.

However the class of the output of the mpfr function is also called mpfr:

>>> f.__class__
mpfr

But this mpfr isn't the mpfr function in the main namespace:

>>> type(f) == mpfr
False

So far I have only managed to check whether or not a variable is an instance of mpfr by creating an empty mpfr instance and use its __class__ attribute:

isinstance(f, mpfr().__class__)

How can I access <class 'mpfr'> directly?


Solution

  • Based on quick experiment I tried on python REPL, I find that the easiest way is to just convert the class name mpfr into string, and compare it with string comparison:

    $ python3
    Python 3.9.7 (default, Aug 31 2021, 13:28:12) 
    [GCC 11.1.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from gmpy2 import mpfr
    >>> f = mpfr('0.5')
    >>> f.__class__
    <class 'mpfr'>
    >>> str(f.__class__)
    "<class 'mpfr'>"
    >>> str(f.__class__) == "<class 'mpfr'>"
    True
    >>>
    

    Alternatively, if you don't want to use __class__ because it's supposed to be private data member, then you can use type(f) instead:

    >>> str(type(f)) == "<class 'mpfr'>"
    True
    

    Or another alternative if you don't care about creating new instance of mpfr but prefer syntactic sugar:

    >>> type(f) == type(mpfr())
    True