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

123 Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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
0
On

The answer by @PYC is correct and will work with the current version and the next major release.

This has been fixed in the next release of gmpy2. Wheels for 2.1.0rc1 are currently available. rc2 will be released soon to fix compatibility issues on some platforms.

It can be installed with the command

pip install gmpy2==2.1.0rc1

or the equivalent pip command appropriate for your system.

0
On

I think because mpfr is a function thats why isinstance() wasn't able to check, this is probably gonna work:

isinstance(f, type(mpfr()))