[FIXED] <class 'float'> versus 'float' in Python type annotations

Issue

When I try to compare the type annotations of an abstract base class and an implementation, I sometimes get two different type annotations with inspect.getfullargspec().

Here is the abstract base class and below a stub of the implementation:


import abc
from typing import List, Tuple


class Abstract(abc.ABC):
    @abc.abstractmethod
    def get_hscodes(self, *, confidence_threshold: float = 0.0, **kwargs):
        pass


class Concrete(Abstract):
    def get_hscodes(self, *, confidence_threshold: float = 0.0, **kwargs):
        likely = self.get_likely_hscodes(confidence_threshold=confidence_threshold, **kwargs)
        return [i[0] if i else (None, 0.0) for i in likely]

    def get_likely_hscodes(
        self, *, confidence_threshold: float = 0.0, **kwargs
    ) -> List[List[Tuple]]:
        pass

Now if I run:

import inspect

print(inspect.getfullargspec(Abstract.get_hscodes))
print(inspect.getfullargspec(Concrete.get_hscodes))

I'm getting differing results:

FullArgSpec(args=['self'], varargs=None, varkw='kwargs', defaults=None, kwonlyargs=['confidence_threshold'], kwonlydefaults={'confidence_threshold': 0.0}, annotations={'confidence_threshold': <class 'float'>})
FullArgSpec(args=['self'], varargs=None, varkw='kwargs', defaults=None, kwonlyargs=['confidence_threshold'], kwonlydefaults={'confidence_threshold': 0.0}, annotations={'confidence_threshold': 'float'})

I tried Python 3.8.13 on both Windows and Linux.

Why am I sometimes getting <class 'float'> and sometimes just float? I have difficulties to even reproduce the problem and don't know where to look for the reason.


Solution

If you have an from __future__ import annotations statement in your implementation file this result can be expected.



Answered By - Robin Gugel
Answer Checked By - Robin (Python.Easybugfix Admin)

Related Posts

Post a Comment