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?
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:
Alternatively, if you don't want to use
__class__
because it's supposed to be private data member, then you can usetype(f)
instead:Or another alternative if you don't care about creating new instance of mpfr but prefer syntactic sugar: