4

I've got 2 class definitions:

class Foo:
  def __init__(self, bar: Bar):
    # some code

class Bar:
  def __init__(self, foo: Foo):
    # some more code

I want to specify the types of the arguments. When I try to run that code I get "using variable 'Bar' before assignment" error.

Is it possible to tell the interpreter that Bar is defined a few lines below?

  • 1
    No, there is no hoisting. However, for type annotations in older versions you can simply use a string, in newer versions, `from __future__ import annotations` which will give you the behavior of postponed evaluation of annotations. – juanpa.arrivillaga Dec 09 '19 at 20:49

1 Answers1

4

If you are using Python version 3.7 or later you can add the following to the top of your file

from __future__ import annotations

https://www.python.org/dev/peps/pep-0563/#enabling-the-future-behavior-in-python-3-7

Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
  • 2
    ...and for prior versions, simply use a string with the class name. The 3rdy party tools that deal with annotations will handle that. – jsbueno Dec 09 '19 at 20:44