Python attr 模块,Factory() 实例源码

我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用attr.Factory()

项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def test_structure_simple_from_dict_default(converter, cl_and_vals, data):
    """Test structuring non-nested attrs classes with default value."""
    cl, vals = cl_and_vals
    obj = cl(*vals)
    attrs_with_defaults = [a for a in fields(cl)
                           if a.default is not NOTHING]
    to_remove = data.draw(lists(elements=sampled_from(attrs_with_defaults),
                                unique=True))

    for a in to_remove:
        if isinstance(a.default, Factory):
            setattr(obj, a.name, a.default.factory())
        else:
            setattr(obj, a.name, a.default)

    dumped = asdict(obj)

    for a in to_remove:
        del dumped[a.name]

    assert obj == converter.structure(dumped, cl)
项目:niceman    作者:ReproNim    | 项目源码 | 文件源码
def factory(distribution_type, provenance=None):
        """
        Factory method for creating the appropriate Orchestrator sub-class
        based on format type.

        Parameters
        ----------
        distribution_type : string
            Type of distribution subclass to create. Current options are:
            'conda', 'debian', 'neurodebian', 'pypi'
        provenance : dict
            Keyword args to be passed to initialize class instance 

        Returns
        -------
        distribution : object
            Distribution class or its instance (when provenance is not None)
        """
        class_name = distribution_type.capitalize() + 'Distribution'
        module = import_module('niceman.distributions.' + distribution_type.lower())
        class_ = getattr(module, class_name)
        return class_ if provenance is None else class_(**provenance)
项目:trio    作者:python-trio    | 项目源码 | 文件源码
def test_AsyncResource_defaults():
    @attr.s
    class MyAR(tabc.AsyncResource):
        record = attr.ib(default=attr.Factory(list))

        async def aclose(self):
            self.record.append("ac")

    async with MyAR() as myar:
        assert isinstance(myar, MyAR)
        assert myar.record == []

    assert myar.record == ["ac"]
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def just_class(tup):
    # tup: Tuple[List[Tuple[_CountingAttr, Strategy]],
    #            Tuple[Type, Sequence[Any]]]
    nested_cl = tup[1][0]
    nested_cl_args = tup[1][1]
    default = attr.Factory(lambda: nested_cl(*nested_cl_args))
    combined_attrs = list(tup[0])
    combined_attrs.append((attr.ib(type=nested_cl, default=default),
                           just(nested_cl(*nested_cl_args))))
    return _create_hyp_class(combined_attrs)
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def list_of_class(tup):
    nested_cl = tup[1][0]
    nested_cl_args = tup[1][1]
    default = attr.Factory(lambda: [nested_cl(*nested_cl_args)])
    combined_attrs = list(tup[0])
    combined_attrs.append((attr.ib(type=List[nested_cl], default=default),
                           just([nested_cl(*nested_cl_args)])))
    return _create_hyp_class(combined_attrs)
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def dict_of_class(tup):
    nested_cl = tup[1][0]
    nested_cl_args = tup[1][1]
    default = attr.Factory(lambda: {"cls": nested_cl(*nested_cl_args)})
    combined_attrs = list(tup[0])
    combined_attrs.append((attr.ib(type=Dict[str, nested_cl], default=default),
                           just({'cls': nested_cl(*nested_cl_args)})))
    return _create_hyp_class(combined_attrs)
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def just_class(tup):
    nested_cl = tup[1][0]
    default = attr.Factory(nested_cl)
    combined_attrs = list(tup[0])
    combined_attrs.append((attr.ib(default=default), st.just(nested_cl())))
    return _create_hyp_class(combined_attrs)
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def dict_of_class(tup):
    nested_cl = tup[1][0]
    default = attr.Factory(lambda: {"cls": nested_cl()})
    combined_attrs = list(tup[0])
    combined_attrs.append((attr.ib(default=default),
                          st.just({'cls': nested_cl()})))
    return _create_hyp_class(combined_attrs)
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def dict_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields dictionaries
    for that attribute. The dictionaries map strings to integers.
    """
    default = NOTHING
    val_strat = st.dictionaries(keys=st.text(), values=st.integers())
    if defaults is True or (defaults is None and draw(st.booleans())):
        default_val = draw(val_strat)
        default = attr.Factory(lambda: default_val)
    return ((attr.ib(default=default), val_strat))
项目:reobject    作者:onyb    | 项目源码 | 文件源码
def Field(*args, default=attr.NOTHING, **kwargs):
    if callable(default):
        default = attr.Factory(default)

    return attr.ib(*args, default=default, **kwargs)
项目:trip-based-public-transit-routing-algo    作者:mk-fg    | 项目源码 | 文件源码
def attr_init(factory_or_default=attr.NOTHING, **attr_kws):
    if callable(factory_or_default): factory_or_default = attr.Factory(factory_or_default)
    return attr.ib(default=factory_or_default, **attr_kws)
项目:niceman    作者:ReproNim    | 项目源码 | 文件源码
def TypedList(type_):
    """A helper to generate an attribute which would be with list factory 
    but also defining a type in its metadata
    """
    return attr.ib(default=Factory(list), metadata={'type': type_})


#
# Models
#