Skip to content

schema-codegen: Types implementing interfaces generated at end of file cause NameError when referenced by other typesΒ #4191

@sanlil

Description

@sanlil

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.
  • FooContainer is generated next (because it follows schema order), with foo: Foo.
  • Later in the file, after schema = strawberry.Schema(...), Foo is 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: str

Result:

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions