1

I'm working in Python 3.7 and have something like this

class A(object):

  def __init__(self, value: int):
    self.value = value
  
  @classmethod
  def factory(cls, value: int) -> A:
    return A(value=value)

Yes, it's a contrived example, but I'm essentially trying to annotate the factory function to state that it returns an instance of A, however, this fails when I attempt to run the flake8 linter over the file as it complains that A isn't defined.

Is there some way to annotate this function such that the linter won't complain?

a_guest
  • 34,165
  • 12
  • 64
  • 118
John Allard
  • 3,564
  • 5
  • 23
  • 42

1 Answers1

4

You can avoid this by annotating with 'A' instead:

class A:
    @classmethod
    def factory(cls, value: int) -> 'A':
        ...

Alternatively you can use __future__ annotations:

from __future__ import annotations

and keep annotating with A.

a_guest
  • 34,165
  • 12
  • 64
  • 118
  • 1
    not sure who downvoted you but you're correct, more information is here https://stackoverflow.com/questions/33533148/how-do-i-specify-that-the-return-type-of-a-method-is-the-same-as-the-class-itsel – John Allard Sep 03 '20 at 18:15
  • I downvoted because the answerer marked as a duplicate and then copied the answer from the duplicate to get free rep. – anthony sottile Sep 03 '20 at 21:53
  • @AnthonySottile Nope, it was the other way round, I answered the question then I discovered the duplicate. – a_guest Sep 04 '20 at 22:23
  • generally you should delete your answer then – anthony sottile Sep 04 '20 at 22:27
  • @AnthonySottile Where did you get that information? [Other people](https://meta.stackexchange.com/q/132600/397492) seem to think differently. – a_guest Sep 08 '20 at 07:34
  • here's [newer advice](https://meta.stackoverflow.com/q/266551/812183) -- but generally when there's nothing added by an answer or the question over the duplicate I'll self-delete and save the roomba some trouble – anthony sottile Sep 08 '20 at 07:47
  • @AnthonySottile Well we have different opinions then. I think only bad or wrong content should be deleted. 10k+ rep users can view deleted content and the fact that an answer has been deleted carries some (mis)information: a user might think its content is wrong when it's not. – a_guest Sep 08 '20 at 12:50