Skip to content

Commit

Permalink
docs: Add type-based solution to forward-ref in generic base
Browse files Browse the repository at this point in the history
  • Loading branch information
pawamoy committed Nov 25, 2024
1 parent 6f22ad8 commit 1e2fcad
Showing 1 changed file with 30 additions and 9 deletions.
39 changes: 30 additions & 9 deletions docs/guide/users/recommendations/python-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -413,17 +413,38 @@ Python's type system will let you use forward references in generic types when t

While Griffe will load this code without error, the `'Bar'` forward reference won't be resolved to the actual `Bar` class. As a consequence, downstream tools like documentation renderers won't be able to output a link to the `Bar` class. We therefore recommend to avoid using forward references in base classes, if possible.

Instead, you can try to declare or import the `Bar` class earlier, or make `FooBar` generic again but with a default type:
Instead, you can try one of the following approach:

```python
class Foo[T]:
...
- declare or import the `Bar` class earlier
- declare a proper type:

```python
class Foo[T]:
...

class FooBar[T=Bar](Foo[T]):
...

type TBar = Bar

class Bar:
...
```

class FooBar(Foo[TBar]):
...


class Bar:
...
```

- make `FooBar` generic again but with a default type:

```python
class Foo[T]:
...


class FooBar[T=Bar](Foo[T]):
...


class Bar:
...
```

0 comments on commit 1e2fcad

Please sign in to comment.