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

[yaml] add better error message for python MapToFields expression #33405

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
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
9 changes: 6 additions & 3 deletions sdks/python/apache_beam/yaml/yaml_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,10 +297,13 @@ def _expand_python_mapping_func(
# TODO(robertwb): Consider constructing a single callable that takes
# the row and returns the new row, rather than invoking (and unpacking)
# for each field individually.
source = '\n'.join(['def fn(__row__):'] + [
f' {name} = __row__.{name}'
source = '\n'.join(['def fn(__row__):'] + [' try:'] + [
f' {name} = __row__.{name}'
for name in original_fields if name in expression
] + [' return (' + expression + ')'])
] + [f' return ({expression})'] + [' except NameError as e:'] + [
f' raise ValueError(f"{{e}}. Valid values include '
f'{original_fields}")'
])

else:
source = callable
Expand Down
22 changes: 22 additions & 0 deletions sdks/python/apache_beam/yaml/yaml_mapping_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,28 @@ def test_drop(self):
beam.Row(label='389a', rank=2),
]))

def test_name_error(self):
with self.assertRaisesRegex(
ValueError,
f".*error_field.*is not defined.*{'.*'.join(DATA[0].as_dict().keys())}"
):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
output = (
p
| beam.Create(DATA)
| YamlTransform(
'''
type: MapToFields
config:
language: python
fields:
new_field: error_field
append: true
drop: [conductor]
'''))
self.assertFalse(output)

def test_filter(self):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
Expand Down
Loading