Skip to content

Commit afa6ea9

Browse files
authored
Merge pull request #60 from ben-denham/friendly-local-class-error
Raise a friendly error for dynamically defined classes as a task types
2 parents b7e3d7f + 869941a commit afa6ea9

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

labtech/serialization.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,16 @@ def deserialize_enum(self, serialized: dict[str, jsonable]) -> Enum:
122122
return enum_cls[name]
123123

124124
def serialize_class(self, cls: type) -> jsonable:
125+
if '<locals>' in cls.__qualname__:
126+
raise SerializationError(
127+
(f'Unable to serialize class "{cls.__qualname__}" because it was defined in a function. '
128+
'Please ensure all task and parameter classes are defined at the top-level of a module.')
129+
)
130+
131+
if '>' in cls.__qualname__:
132+
# This should never happen, but is here for safety.
133+
raise SerializationError('Unexpected ">" in class __qualname__')
134+
125135
# Handle nested classes by splitting class nesting path by ">".
126136
return f'{cls.__module__}.{cls.__qualname__.replace(".", ">")}'
127137

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import pytest
2+
3+
from labtech.exceptions import SerializationError
4+
from labtech.serialization import Serializer
5+
6+
7+
class TestSerializer:
8+
9+
class TestSerializeClass:
10+
11+
def test_local_object(self):
12+
13+
class Example:
14+
pass
15+
16+
serializer = Serializer()
17+
with pytest.raises(SerializationError, match=f'Unable to serialize class "{Example.__qualname__}" because it was defined in a function.'):
18+
serializer.serialize_class(Example)

0 commit comments

Comments
 (0)