Skip to content

Commit 31a2e8f

Browse files
committed
Allow decorator usage; document register_row is preferred
1 parent d6172eb commit 31a2e8f

2 files changed

Lines changed: 29 additions & 4 deletions

File tree

sdks/python/apache_beam/coders/row_coder_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,13 +60,13 @@
6060
("one_more_field", typing.Optional[str])])
6161

6262

63+
@coders_registry.register_row
6364
class People(typing.NamedTuple):
6465
primary: Person
6566
partner: typing.Optional[Person]
6667

6768

68-
coders_registry.register_coder(Person, RowCoder)
69-
coders_registry.register_coder(People, RowCoder)
69+
coders_registry.register_row(Person)
7070

7171

7272
class RowCoderTest(unittest.TestCase):

sdks/python/apache_beam/coders/typecoders.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,19 @@ def _normalize_typehint_type(typehint_type):
124124
def register_coder(
125125
self, typehint_type: Any,
126126
typehint_coder_class: Type[coders.Coder]) -> None:
127-
"Register a user type with a coder"
127+
"""
128+
Register a user type with a coder.
129+
130+
Typical usage::
131+
132+
class MyCustomType:
133+
pass
134+
135+
coders.registry.register_coder(MyCustomType, MyCustomCoder)
136+
137+
To register a supported user type (data class or named tuple) with Beam Row,
138+
use :meth:`register_row` instead, as it registers both coder and schema.
139+
"""
128140
if not isinstance(typehint_coder_class, type):
129141
raise TypeError(
130142
'Coder registration requires a coder class object. '
@@ -134,11 +146,23 @@ def register_coder(
134146
self._register_coder_internal(
135147
self._normalize_typehint_type(typehint_type), typehint_coder_class)
136148

137-
def register_row(self, typehint_type: Any) -> None:
149+
def register_row(self, typehint_type: type[Any]) -> type[Any]:
138150
"""
139151
Register a user type with a Beam Row.
140152
141153
This registers the type with a RowCoder and register its schema.
154+
155+
Register a dataclass::
156+
157+
@typecoders.registry.register_row
158+
@dataclass
159+
class MyDataClass:
160+
id: int
161+
name: str
162+
163+
Register a named tuple::
164+
165+
coders.registry.register_row(MyNamedTuple)
142166
"""
143167
from apache_beam.coders import RowCoder
144168
from apache_beam.typehints.schemas import typing_to_runner_api
@@ -148,6 +172,7 @@ def register_row(self, typehint_type: Any) -> None:
148172
# This call generated a schema id for the type and register it with
149173
# schema registry
150174
typing_to_runner_api(typehint_type)
175+
return typehint_type
151176

152177
def get_coder(self, typehint: Any) -> coders.Coder:
153178
if typehint and typehint.__module__ == '__main__':

0 commit comments

Comments
 (0)