-
-
Notifications
You must be signed in to change notification settings - Fork 610
Description
Describe the Bug
When using strawberry schema-codegen to generate Python code from a GraphQL schema, types that implement an interface are emitted at the end of the generated file (after the schema = strawberry.Schema(...) line), regardless of where they appear in the schema or whether other types reference them.
If another type in the schema has a field that references such an implementing type, that referencing type is generated in schema order, i.e. before the implementing type. At runtime, Python then tries to resolve the type hint when the referencing class is defined, but the implementing type is not defined yet, leading to a NameError.
Minimal reproduction
GraphQL schema:
interface Bar {
bar: String!
}
type Foo implements Bar {
bar: String!
}
type FooContainer {
foo: Foo!
}Generated Python (simplified):
Bar(interface) is generated in order.FooContaineris generated next (because it follows schema order), withfoo: Foo.- Later in the file, after
schema = strawberry.Schema(...),Foois generated.
So the generated file looks conceptually like:
@strawberry.interface
class Bar:
bar: str
@strawberry.type
class FooContainer:
foo: Foo # NameError: name 'Foo' is not defined
# ... schema = strawberry.Schema(...) ...
@strawberry.type
class Foo(Bar):
bar: strResult:
NameError: name 'Foo' is not defined
when importing the generated module (e.g. when FooContainer is defined and Python evaluates the annotation foo: Foo).
Expected behaviour
Implementing types (e.g. Foo) should be generated before any type that references them (e.g. FooContainer), so that all names are defined when the module is loaded. In other words, the codegen should topologically sort generated types so that dependencies (including interface implementers) are defined before their dependents.
System Information
- Operating system: macOS 26.2
- Python version: 3.13
- Strawberry version: strawberry-graphql[cli,fastapi]>=0.291.0
- Command:
strawberry schema-codegen schema.graphqls -o schema.py