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

adding doctest to .rst files #3481

Merged
merged 1 commit into from
Nov 15, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 28 additions & 28 deletions docs/api_reference/flax.cursor.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,42 +8,42 @@ data structures, compared to making many nested ``dataclasses.replace`` calls.

To illustrate, consider the example below::

from flax.cursor import cursor
import dataclasses
from typing import Any
>>> from flax.cursor import cursor
>>> import dataclasses
>>> from typing import Any

@dataclasses.dataclass(frozen=True)
class A:
x: Any
>>> @dataclasses.dataclass(frozen=True)
>>> class A:
... x: Any

a = A(A(A(A(A(A(A(0)))))))
>>> a = A(A(A(A(A(A(A(0)))))))

To replace the int ``0`` using ``dataclasses.replace``, we would have to write many nested calls::

a2 = dataclasses.replace(
a,
x=dataclasses.replace(
a.x,
x=dataclasses.replace(
a.x.x,
x=dataclasses.replace(
a.x.x.x,
x=dataclasses.replace(
a.x.x.x.x,
x=dataclasses.replace(
a.x.x.x.x.x,
x=dataclasses.replace(a.x.x.x.x.x.x, x=1),
),
),
),
),
),
)
>>> a2 = dataclasses.replace(
... a,
... x=dataclasses.replace(
... a.x,
... x=dataclasses.replace(
... a.x.x,
... x=dataclasses.replace(
... a.x.x.x,
... x=dataclasses.replace(
... a.x.x.x.x,
... x=dataclasses.replace(
... a.x.x.x.x.x,
... x=dataclasses.replace(a.x.x.x.x.x.x, x=1),
... ),
... ),
... ),
... ),
... ),
... )

The equivalent can be achieved much more simply using the Cursor API::

a3 = cursor(a).x.x.x.x.x.x.x.set(1)
assert a2 == a3
>>> a3 = cursor(a).x.x.x.x.x.x.x.set(1)
>>> assert a2 == a3

The Cursor object keeps tracks of changes made to it and when ``.build`` is called,
generates a new object with the accumulated changes. Basic usage involves
Expand Down