Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like js hoisting for class definitions in python? [duplicate]

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?

like image 879
Maksymilian K Avatar asked Oct 20 '25 03:10

Maksymilian K


1 Answers

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

like image 119
Iain Shelvington Avatar answered Oct 23 '25 00:10

Iain Shelvington