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

Recursion of Category in Category creates pydantic error #1

Open
torogi94 opened this issue Mar 19, 2022 · 1 comment
Open

Recursion of Category in Category creates pydantic error #1

torogi94 opened this issue Mar 19, 2022 · 1 comment
Labels
bug Something isn't working

Comments

@torogi94
Copy link
Member

If hinting to Category with Category , this error occurs:
Exception has occurred: NameError
name 'Category' is not defined

If hinting to Category with "Category" (like you usually do in Python), this error occurs:
Exception has occurred: TypeError
issubclass() arg 1 must be a class

@torogi94 torogi94 added the bug Something isn't working label Mar 19, 2022
@JR-1991
Copy link
Contributor

JR-1991 commented Mar 20, 2022

Self-Referencing annotations can be handled quite nice with Pedantic (see doc). Whenever you want to reference the self-class in an annotation, simply pass it as a string and it works. Here is an overexagurated example:

import pydantic
import enum
import typing
import json

class CategoryType(pydantic.BaseModel):
    """Recursion is possible when the type is given as a string"""
    
    foo: str
    bar: str
    category: typing.Optional['CategoryType'] = None

# Create recursion objects
category = CategoryType(foo="foo", bar="bar")
top_category = CategoryType(foo="top_foo", bar="top_bar")
toptop_category = CategoryType(foo="toptop_foo", bar="toptop_bar")

# Get them together
category.category = top_category
category.category.category = toptop_category

JSON

{
   "foo": "foo",
   "bar": "bar",
   "category": {
      "foo": "top_foo",
      "bar": "top_bar",
      "category": {
         "foo": "toptop_foo",
         "bar": "toptop_bar",
         "category": null
      }
   }
}

This is by far one of the best libraries I've ever used. Many kudos!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants