Comments (8)
Hi @omaxx
There are two problems here, but they are solvable. Fortunately for us.
Firstly, a class created using make_dataclass
doesn't contain correct information about the module in which it was created until you specify it in the namespace
parameter. This is what you see in the error message:
AttributeError: module 'types' has no attribute 'User'
To fix this you should pass the correct module name which is the module where your Device
class exists:
make_dataclass(..., namespace={"__module__": __name__, ...})
Secondly, to deserialize an object of the User
class, we need to have something like a reference to this User
class, since we need to call its from_dict
method. The qualified name is exactly this reference. But by default make_dataclass
creates an attribute __qualname__
equal to the class name, well, "User". The namespace of the module doesn't have this name, so you can't call something like your.module.User.from_dict
. To fix this you should specify the correct qualified name in the namespace
parameter. This part is tricky. In your example the User
class isn't located in the namespace of the Device
class, because it's created in the value of the "user" field. If it's really what you want, qualified name of such a class can be obtained with the following code:
f'{__qualname__}.__annotations__["user"]'
To summarize, your example needs to be modified as follows to make it work:
@dataclass
class Device(DataClassDictMixin):
name: str
user: make_dataclass(
'User',
[
("name", str),
("pw", str),
],
namespace={
"__module__": __name__,
"__qualname__": f'{__qualname__}.__annotations__["user"]',
},
bases=(DataClassDictMixin,)
)
device = Device.from_dict({"name": "device", "user": {"name": "jon", "pw": "snow"}})
print(device)
# Device(name='device', user=Device.__annotations__["user"](name='jon', pw='snow'))
print(device.to_dict())
# {'name': 'device', 'user': {'name': 'jon', 'pw': 'snow'}}
If it's not essential for you to create the User
class directly in the field value, then you can move this operation to the module level. In this case, the code will be simplified:
User = make_dataclass(
'User',
[
("name", str),
("pw", str),
],
namespace={
"__module__": __name__,
},
bases=(DataClassDictMixin,)
)
@dataclass
class Device(DataClassDictMixin):
name: str
user: User
device = Device.from_dict({"name": "device", "user": {"name": "jon", "pw": "snow"}})
print(device)
# Device(name='device', user=User(name='jon', pw='snow'))
print(device.to_dict())
# {'name': 'device', 'user': {'name': 'jon', 'pw': 'snow'}}
Well, after all this investigation, I would like to finally know what are you doing if you need to create dataclasses in such a non-standard way? :)
from mashumaro.
Hi @Fatal1ty
I only try to figure out how is it possible to define dataclass with hierarchical structure in the simplest way.
from mashumaro.
Hi @Fatal1ty
I only try to figure out how is it possible to define dataclass with hierarchical structure in the simplest way.
What do you mean by hierarchical structure? Using make_dataclass
can hardly be called the simplest solution. I can help you find the better way if you elaborate more on what you are trying to achieve.
from mashumaro.
Under "hierarchical structure" I mean case when dataclass has fields with type of another dataclass, and that dataclass also could have dataclass fields. Defining field dataclass type inside fields for me looks more readable.
@dataclass
class Device(DataClassDictMixin):
name: str
user: make_dataclass('User', [
("name", str),
("pw", str),
], bases=(DataClassDictMixin,))
vs
@dataclass
class User(DataClassDictMixin):
name: str
pw: str
@dataclass
class Device(DataClassDictMixin):
name: str
user: User
from mashumaro.
Ah, I see. What about this variant?
@dataclass
class Device(DataClassDictMixin):
name: str
user: "User"
@dataclass
class User(DataClassDictMixin):
name: str
credentials: "Credentials"
@dataclass
class Credentials(DataClassDictMixin):
login: str
pw: str
data = {
"name": "device",
"user": {
"name": "jon",
"credentials": {"login": "john", "pw": "snow"}
}
}
device = Device.from_dict(data)
# Device(
# name='device',
# user=User(
# name='john',
# credentials=Device.User.Credentials(
# login='john',
# pw='snow'
# )
# )
# )
assert device.to_dict() == data
from mashumaro.
Firstly, a class created using
make_dataclass
doesn't contain correct information about the module in which it was created until you specify it in thenamespace
parameter. This is what you see in the error message:AttributeError: module 'types' has no attribute 'User'To fix this you should pass the correct module name which is the module where your
Device
class exists:make_dataclass(..., namespace={"__module__": __name__, ...})
Meanwhile, incorrect __module__
attribute is apparently going to be fixed in python/cpython#102103
from mashumaro.
Ah, I see. What about this variant?
@dataclass class Device(DataClassDictMixin): name: str user: "User" @dataclass class User(DataClassDictMixin): name: str credentials: "Credentials" @dataclass class Credentials(DataClassDictMixin): login: str pw: str
Thank you! This variant is better!
from mashumaro.
Ok, good to hear that. If there is another problem, open an issue. Iām closing this one.
from mashumaro.
Related Issues (20)
- field metadata "description" does not show up in built json output HOT 1
- collections.OrderedDict is not hashable HOT 10
- Allow discrimination based on a key that is not part of the model HOT 8
- Raise the inner exception when parsing nested dataclasses HOT 2
- Performance of json_schema generation HOT 5
- collections.OrderedDict is not hashable when using inside typing_extensions.Annotated on Python < 3.9
- Overridden serialization methods doesn't work in JSON Schema for optional fields and inner dataclasses
- Third party default is not reflected in the generated JSON Schema
- Add support for ForwardRef HOT 6
- Drop Python 3.7 support
- Allow basic types used as serialization methods to be reflected in the JSON schema
- Switch to ruff from flake8
- Comprehension inlining on Python 3.12.0rc1 breaks some tests HOT 1
- Add support for Python 3.12
- Add support for PEP 696 HOT 1
- Can immutable dataclasses be hashed as dictionary keys? HOT 4
- Add an option to omit values equal to defaults on serialization
- Add an option to avoid collection data types copying
- Add support for LiteralString
- Generic dataclasses with Hashable typevar bound do not work HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
š Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. ššš
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ā¤ļø Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mashumaro.