1

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?

2
  • what about if f.__class__ == 'mpfr' : ...? Commented Sep 20, 2021 at 6:26
  • @Kristian f.__class__ == 'mpfr' is False, the attribute isn't a str... Commented Sep 20, 2021 at 6:37

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

isinstance(f, type(mpfr()))

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.