Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Self-referencing model in python 3.6 fails #616

Closed
vlcinsky opened this issue Jun 22, 2019 · 3 comments

Comments

Projects
None yet
2 participants
@vlcinsky
Copy link
Contributor

commented Jun 22, 2019

Question/Bug

  • OS: Debian Stretch
  • Python version: 3.6.5
  • Pydantic version : 0.29

I am not sure, self-referencing models are supported under python 3.6.x. The doc seems to describe it, but testing it it failed for me:

Using self-contained script from doc saved as self_ref.py:

from pydantic import BaseModel

class Foo(BaseModel):
    a: int = 123
    #: The sibling of `Foo` is referenced by string
    sibling: 'Foo' = None

Foo.update_forward_refs()

print(Foo())
#> Foo a=123 sibling=None
print(Foo(sibling={'a': '321'}))
#> Foo a=123 sibling=<Foo a=321 sibling=None>

Run under python 3.7.3 (OK)

(py37) $ python self_ref.py
Foo a=123 sibling=None
Foo a=123 sibling=<Foo a=321 sibling=None>

Run under python 3.6.5 (failure)

(py36) $ python self_ref.py
Traceback (most recent call last):
  File "pydantic/validators.py", line 431, in pydantic.validators.find_validators
TypeError: issubclass() arg 1 must be a class

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "self_ref.py", line 3, in <module>
    class Foo(BaseModel):
  File "pydantic/main.py", line 206, in pydantic.main.MetaModel.__new__
  File "pydantic/fields.py", line 130, in pydantic.fields.Field.infer
  File "pydantic/fields.py", line 107, in pydantic.fields.Field.__init__
  File "pydantic/fields.py", line 173, in pydantic.fields.Field.prepare
  File "pydantic/fields.py", line 262, in pydantic.fields.Field._populate_validators
  File "pydantic/validators.py", line 440, in find_validators
RuntimeError: error checking inheritance of 'Foo' (type: str)
@samuelcolvin

This comment has been minimized.

Copy link
Owner

commented Jun 24, 2019

Try from __future__ import annotations

If that doesn't work, I'm afraid we don't support it in 3.6.

@vlcinsky

This comment has been minimized.

Copy link
Contributor Author

commented Jun 24, 2019

According to PEP563 is this supported since python 3.7.

This was the reason, it did not work in python 3.6.

It would be worth a note in the docs.

@samuelcolvin

This comment has been minimized.

Copy link
Owner

commented Jun 24, 2019

Absolutely, PR welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.