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

Support field names that aren't valid Python identifiers #139

Closed
nickretallack opened this Issue Feb 5, 2015 · 3 comments

Comments

Projects
None yet
3 participants
@nickretallack

nickretallack commented Feb 5, 2015

I want to support a field called "from", but I can't do this in marshmallow because it would cause a syntax error:

class MySchema(Schema):
    from = fields.Nested(OtherSchema, attribute="my_attribute")

This got me thinking -- marshmallow is kind of backwards, isn't it? The field that comes in from the outside world is the one that has to be specified as a valid Python identifier, and the field that you're actually going to work with in your code is specified as a string. Shouldn't they be swapped? I'm sure other folks are going to want to parse in or write out a value that isn't a valid Python identifier sometimes.

class MySchema(Schema):
    my_attribute = fields.Nested(OtherSchema, field="from")

This could even be made backward compatible with existing Marshmallow stuff, like so:

  • If neither "field" nor "attribute" are specified, the field and attribute values are both the same as the lvalue, so there's no issue.
  • If "attribute" is specified, the lvalue is used for "field"
  • if "field" is specified, the lvalue is used for "attribute"

Probably harder for you to actually implement this sorta thing though, but it's a thought.

@sloria

This comment has been minimized.

Member

sloria commented Feb 10, 2015

Another possible solution would be to allow adding fields in a dict. Something like:

class MySchema(Schema):
    class Meta:
        add_fields = {'from': fields.Nested(OtherSchema, attribute='my_attribute')

Would have to think harder about what to name the option, but I believe this can be implemented without adding too much complexity.

@sloria

This comment has been minimized.

Member

sloria commented Mar 1, 2015

The include option has been added in 41b8ed3 . You can now do:

class MySchema(Schema):
    class Meta:
        include = {
            'from': fields.Nested(OtherSchema, attribute="my_attribute")
        }

@sloria sloria closed this Mar 1, 2015

@taion

This comment has been minimized.

Contributor

taion commented Mar 17, 2015

BTW, this is very helpful for anybody who wants to follow the JSON API recommendations of dasherizing all attribute names as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment