Convert Figma logo to code with AI

marshmallow-code logomarshmallow

A lightweight library for converting complex objects to and from simple Python datatypes.

6,992
624
6,992
179

Top Related Projects

1,506

A flexible forms validation and rendering library for Python.

20,398

Data validation using Python type hints

79,643

The Web framework for perfectionists with deadlines.

Web APIs for Django. 🎸

Quick Overview

Marshmallow is a lightweight, fast, and flexible object-serialization and deserialization library for Python. It allows you to convert complex data types, such as objects, to and from native Python data types (e.g., dicts, lists, etc.) for easy use in applications.

Pros

  • Flexible and Extensible: Marshmallow provides a wide range of built-in field types and allows for easy customization and extension of the serialization/deserialization process.
  • Validation and Transformation: Marshmallow includes a robust validation system that can be used to ensure data integrity and perform complex transformations on the data.
  • Compatibility with Other Libraries: Marshmallow can be easily integrated with other popular Python libraries, such as SQLAlchemy, Django, and Flask.
  • Lightweight and Performant: Marshmallow is a lightweight library that is designed to be fast and efficient, making it a good choice for high-performance applications.

Cons

  • Learning Curve: Marshmallow has a relatively steep learning curve, especially for developers who are new to the concept of serialization and deserialization.
  • Boilerplate Code: Using Marshmallow can sometimes require writing a significant amount of boilerplate code, which can make the codebase more verbose.
  • Dependency Management: Marshmallow has a number of dependencies, which can make it more challenging to manage the project's dependencies.
  • Limited Support for Nested Structures: While Marshmallow does support nested data structures, the implementation can be complex and may require additional customization.

Code Examples

Here are a few examples of how to use Marshmallow:

from marshmallow import Schema, fields

class UserSchema(Schema):
    name = fields.Str()
    email = fields.Email()
    age = fields.Int()

user_data = {
    'name': 'John Doe',
    'email': 'john@example.com',
    'age': 30
}

schema = UserSchema()
result = schema.dump(user_data)
print(result)
# Output: {'name': 'John Doe', 'email': 'john@example.com', 'age': 30}

This example demonstrates how to define a simple schema using Marshmallow and use it to serialize a dictionary of user data.

from marshmallow import Schema, fields

class BookSchema(Schema):
    title = fields.Str()
    author = fields.Str()
    publication_date = fields.Date()

book_data = {
    'title': 'The Great Gatsby',
    'author': 'F. Scott Fitzgerald',
    'publication_date': '1925-04-10'
}

schema = BookSchema()
result = schema.load(book_data)
print(result)
# Output: {'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'publication_date': datetime.date(1925, 4, 10)}

This example demonstrates how to use Marshmallow to deserialize a dictionary of book data into a Python object.

from marshmallow import Schema, fields

class AddressSchema(Schema):
    street = fields.Str()
    city = fields.Str()
    state = fields.Str()
    zip_code = fields.Str()

class PersonSchema(Schema):
    name = fields.Str()
    age = fields.Int()
    address = fields.Nested(AddressSchema)

person_data = {
    'name': 'John Doe',
    'age': 30,
    'address': {
        'street': '123 Main St',
        'city': 'Anytown',
        'state': 'CA',
        'zip_code': '12345'
    }
}

schema = PersonSchema()
result = schema.dump(person_data)
print(result)
# Output: {'name': 'John Doe', 'age': 30, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zip_code': '12345'}}

This example demonstrates how to use

Competitor Comparisons

1,506

A flexible forms validation and rendering library for Python.

Pros of WTForms

  • Integrated with web frameworks like Flask and Django
  • Supports HTML form rendering out of the box
  • Extensive field types for various input scenarios

Cons of WTForms

  • Primarily focused on web forms, less versatile for general data serialization
  • More complex setup for non-web applications
  • Limited support for nested structures and complex data types

Code Comparison

WTForms:

from wtforms import Form, StringField, validators

class UserForm(Form):
    username = StringField('Username', [validators.Length(min=4, max=25)])
    email = StringField('Email', [validators.Email()])

Marshmallow:

from marshmallow import Schema, fields, validate

class UserSchema(Schema):
    username = fields.Str(validate=validate.Length(min=4, max=25))
    email = fields.Email()

Both libraries provide ways to define and validate data structures, but WTForms is more focused on web forms, while Marshmallow is more versatile for general data serialization and deserialization. WTForms integrates well with web frameworks and offers HTML rendering, whereas Marshmallow excels in API development and complex data transformations.

20,398

Data validation using Python type hints

Pros of Pydantic

  • Data Validation: Pydantic provides a robust data validation system, ensuring that data conforms to the defined schema, which can be helpful in building reliable and maintainable applications.
  • Type Hints: Pydantic leverages Python's type hints, making it easier to work with and understand the data structures in your codebase.
  • Performance: Pydantic is known for its efficient performance, making it a suitable choice for applications that require fast data processing.

Cons of Pydantic

  • Steeper Learning Curve: Pydantic's feature-rich nature and complex data validation system can have a steeper learning curve compared to Marshmallow, especially for developers new to the concept of data validation.
  • Dependency on Type Hints: Pydantic's reliance on Python's type hints may be a limitation for projects that do not use type hints or prefer a more flexible approach.

Code Comparison

Marshmallow:

from marshmallow import Schema, fields

class UserSchema(Schema):
    name = fields.Str()
    email = fields.Email()

Pydantic:

from pydantic import BaseModel, EmailStr

class User(BaseModel):
    name: str
    email: EmailStr
79,643

The Web framework for perfectionists with deadlines.

Pros of Django

  • Django is a full-featured web framework that provides a comprehensive set of tools and features for building complex web applications, including an ORM, admin interface, and templating engine.
  • Django has a large and active community, with extensive documentation, third-party packages, and community-driven development.
  • Django is highly scalable and can handle high-traffic websites and applications.

Cons of Django

  • Django can be overkill for smaller projects or simple APIs, as it has a steeper learning curve and more features than may be necessary.
  • Django's monolithic architecture can make it more difficult to scale individual components of an application independently.
  • Django's default ORM and database integration may not be the best fit for all use cases, and can require additional configuration or customization.

Code Comparison

Marshmallow:

from marshmallow import Schema, fields

class UserSchema(Schema):
    name = fields.Str()
    email = fields.Email()

Django:

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

Web APIs for Django. 🎸

Pros of Django REST Framework

  • Comprehensive Functionality: Django REST Framework (DRF) provides a wide range of features and functionality out of the box, making it a robust and feature-rich solution for building RESTful APIs.
  • Tight Integration with Django: DRF is designed to work seamlessly with the Django web framework, allowing developers to leverage the existing Django ecosystem and tooling.
  • Extensive Documentation and Community: DRF has a large and active community, with extensive documentation and resources available, making it easier for developers to get started and find solutions to common problems.

Cons of Django REST Framework

  • Increased Complexity: The comprehensive functionality of DRF can also lead to a steeper learning curve, especially for developers who are new to Django or RESTful API development.
  • Performance Overhead: DRF's feature-rich nature can sometimes result in performance overhead, particularly for simple API use cases where a more lightweight solution might be more appropriate.
  • Opinionated Design: DRF has a specific way of doing things, which may not always align with the preferences or requirements of every project or development team.

Code Comparison

Marshmallow:

from marshmallow import Schema, fields

class UserSchema(Schema):
    id = fields.Int(dump_only=True)
    name = fields.Str(required=True)
    email = fields.Email(required=True)

Django REST Framework:

from rest_framework import serializers

class UserSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(required=True)
    email = serializers.EmailField(required=True)

Both the Marshmallow and Django REST Framework examples define a simple user schema with an id, name, and email field. The main differences are in the syntax and the specific field types used, but the overall functionality is similar.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README


marshmallow: simplified object serialization


|pypi| |build-status| |pre-commit| |docs|

.. |pypi| image:: https://badgen.net/pypi/v/marshmallow :target: https://pypi.org/project/marshmallow/ :alt: Latest version

.. |build-status| image:: https://github.com/marshmallow-code/marshmallow/actions/workflows/build-release.yml/badge.svg :target: https://github.com/marshmallow-code/marshmallow/actions/workflows/build-release.yml :alt: Build status

.. |pre-commit| image:: https://results.pre-commit.ci/badge/github/marshmallow-code/marshmallow/dev.svg :target: https://results.pre-commit.ci/latest/github/marshmallow-code/marshmallow/dev :alt: pre-commit.ci status

.. |docs| image:: https://readthedocs.org/projects/marshmallow/badge/ :target: https://marshmallow.readthedocs.io/ :alt: Documentation

marshmallow is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes.

.. code-block:: python

from datetime import date
from pprint import pprint

from marshmallow import Schema, fields


class ArtistSchema(Schema):
    name = fields.Str()


class AlbumSchema(Schema):
    title = fields.Str()
    release_date = fields.Date()
    artist = fields.Nested(ArtistSchema())


bowie = dict(name="David Bowie")
album = dict(artist=bowie, title="Hunky Dory", release_date=date(1971, 12, 17))

schema = AlbumSchema()
result = schema.dump(album)
pprint(result, indent=2)
# { 'artist': {'name': 'David Bowie'},
#   'release_date': '1971-12-17',
#   'title': 'Hunky Dory'}

In short, marshmallow schemas can be used to:

  • Validate input data.
  • Deserialize input data to app-level objects.
  • Serialize app-level objects to primitive Python types. The serialized objects can then be rendered to standard formats such as JSON for use in an HTTP API.

Get It Now

::

$ pip install -U marshmallow

Documentation

Full documentation is available at https://marshmallow.readthedocs.io/ .

Requirements

  • Python >= 3.8

Ecosystem

A list of marshmallow-related libraries can be found at the GitHub wiki here:

https://github.com/marshmallow-code/marshmallow/wiki/Ecosystem

Credits

Contributors

This project exists thanks to all the people who contribute.

You're highly encouraged to participate in marshmallow's development. Check out the Contributing Guidelines <https://marshmallow.readthedocs.io/en/latest/contributing.html>_ to see how you can help.

Thank you to all who have already contributed to marshmallow!

.. image:: https://opencollective.com/marshmallow/contributors.svg?width=890&button=false :target: https://marshmallow.readthedocs.io/en/latest/authors.html :alt: Contributors

Backers

If you find marshmallow useful, please consider supporting the team with a donation. Your donation helps move marshmallow forward.

Thank you to all our backers! [Become a backer_]

.. _Become a backer: https://opencollective.com/marshmallow#backer

.. image:: https://opencollective.com/marshmallow/backers.svg?width=890 :target: https://opencollective.com/marshmallow#backers :alt: Backers

Sponsors

marshmallow is sponsored by Route4Me <https://route4me.com>_.

.. image:: https://github.com/user-attachments/assets/018c2e23-032e-4a11-98da-8b6dc25b9054 :target: https://route4me.com :alt: Routing Planner

Support this project by becoming a sponsor (or ask your company to support this project by becoming a sponsor). Your logo will be displayed here with a link to your website. [Become a sponsor_]

.. _Become a sponsor: https://opencollective.com/marshmallow#sponsor

Professional Support

Professionally-supported marshmallow is now available through the Tidelift Subscription <https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=readme>_.

Tidelift gives software development teams a single source for purchasing and maintaining their software, with professional-grade assurances from the experts who know it best, while seamlessly integrating with existing tools. [Get professional support_]

.. _Get professional support: https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=marshmallow&utm_medium=referral&utm_campaign=github

.. image:: https://user-images.githubusercontent.com/2379650/45126032-50b69880-b13f-11e8-9c2c-abd16c433495.png :target: https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=readme :alt: Get supported marshmallow with Tidelift

Project Links

License

MIT licensed. See the bundled LICENSE <https://github.com/marshmallow-code/marshmallow/blob/dev/LICENSE>_ file for more details.