Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Marshmallow and PyCharm Type Hinting

I'm interested in using the python marshmallow library for data serialization, but I'm running into an issue with PyCharm not being able to suggest the class attributes when the class is constructed using the Schema.load method, as shown in the examples.

Consider the following potentially contrived example:

from marshmallow import Schema, post_load, fields

class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

class UserSchema(Schema):
    name = fields.String(required=True)
    age = fields.Integer(required=True)

    @post_load
    def make_user(self, data, **kwargs):
        return User(**data)

class UserHolder:
    def __init__(self):
        self.user = UserSchema().load({"name": "foo", "age": 42})

class UserHolderConsumer:
    def __init__(self):
        self.user_holder = UserHolder()

    def get_user(self):
        print("Name: {}; Age: {}".format(self.user_holder.user.name, self.user_holder.user.age))

if __name__ == "__main__":
    UserHolderConsumer().get_user()

The code works--meaning the data is there--but PyCharm can't suggest the class attributes. Am I asking too much of PyCharm on this, or am I missing something?

like image 508
mitchute Avatar asked Oct 28 '25 02:10

mitchute


1 Answers

Just for posterity, based on the answer above the following allows this to work.

self.user: UserSchema = UserSchema().load({"name": "foo", "age": 42})
like image 124
mitchute Avatar answered Oct 30 '25 17:10

mitchute