Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Allow callable defaults for any sealer #6

Copy link
Copy link
@dimitern

Description

@dimitern
Issue body actions

First let me say - great library! :) I've been evaluating it as well as attrs for a while now.

I'd like to suggest a possible feature extension: allow callable defaults, which will let you do things like this:

from datetime import datetime
import fields
class Record(fields.Tuple.Username[str].Created[datetime.now].Revision[long].Active[bool]):
    pass

Using types as defaults IMO makes the code more readable. Also assuming the callable takes no arguments, it allows simple initialization at run-time (like with datetime.now).

It's easy to do that with a simple sealer wrapper, like the one below:

from functools import wraps
from fields import factory, tuple_sealer

def with_callable_defaults(sealer):
    """
    Wraps the given `sealer` to support `callable` for any specified default.
    """
    @wraps(sealer)
    def wrapped_sealer(fields, defaults):
        for field, default in defaults.iteritems():
            if callable(default):
                try:
                    defaults[field] = default()
                except TypeError:
                    pass
        return sealer(fields, defaults)
    return wrapped_sealer

Tuple = factory(with_callable_defaults(tuple_sealer))

What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.