Skip to content

Move all public methods on a model into a single namespace #1001

@samuelcolvin

Description

@samuelcolvin

There's currently a tension in pydantic: understandably there's a desire to add more public methods to models, for example iter in #997. But there's also a concern with adding more public methods since they might conflict with fields people want to add, e.g. in the above example it would cause annoyance if someone wanted an iter field (there's an issue about this somewhere, but I can't find it right now, pointer welcome).

Of course this can be partially solve with aliases, but it's still frustrating and confusing.

Potential solutions:

  • make all the methods on models "private" (this is what's done I think on named tuples) so my_model.dict() would become my_model._dict(). This would upset pycharm and perhaps linting tools a lot and would look ugly.
  • move all public methods into a single namespace, e.g. my_model.dict() would become my_model.<whatever>.dict(). Slightly more typing but I think clearest.

Obviously if we do this is would need to be in version 2.

I think the second solution would be the best approach. Questions:

  • do you agree?
  • would it have a performance impact, I guess; yes but small?
  • most importantly: if this is agreed with, what name should we use?

I think something short, preferably one character.

How about m, standing for either "methods" or "model"?

Example of this usage:

from datetime import datetime
from typing import List
from pydantic import BaseModel

class User(BaseModel):
    id: int
    name = 'John Doe'
    signup_ts: datetime = None
    friends: List[int] = []

user = User(id=123)
print(user.m.dict())
print(user.m.schema())

@dmontagu, @MrMrRobat, anyone else; thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    changeSuggested alteration to Pydantic, not a new feature nor a bugfeedback wanted

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions