Python attr.Factory() Examples

The following are 30 code examples of attr.Factory(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module attr , or try the search function .
Example #1
Source File: secrets.py    From environ-config with Apache License 2.0 6 votes vote down vote up
def _get(self, environ, metadata, prefix, name):
        # Delayed loading.
        if self._cfg is None and self._env_name is not None:
            log.debug("looking for env var '%s'." % (self._env_name,))
            self._cfg = _load_ini(
                environ.get(self._env_name, self._env_default)
            )

        ce = metadata[CNF_KEY]
        ic = metadata[CNF_INI_SECRET_KEY]
        section = ic.section

        if ce.name is not None:
            var = ce.name
        else:
            var = "_".join((prefix + (name,)))
        try:
            log.debug("looking for '%s' in section '%s'." % (var, section))
            return _SecretStr(self._cfg.get(section, var))
        except NoOptionError:
            if isinstance(ce.default, attr.Factory):
                return attr.NOTHING
            elif ce.default is not RAISE:
                return ce.default
            raise MissingSecretError(var) 
Example #2
Source File: test_structure_attrs.py    From cattrs with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: test_tcp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_startedListeningLogMessage(self):
        """
        When a port starts, a message including a description of the associated
        factory is logged.
        """
        loggedMessages = self.observe()
        reactor = self.buildReactor()

        @implementer(ILoggingContext)
        class SomeFactory(ServerFactory):
            def logPrefix(self):
                return "Crazy Factory"

        factory = SomeFactory()
        p = self.getListeningPort(reactor, factory)
        expectedMessage = self.getExpectedStartListeningLogMessage(
            p, "Crazy Factory")
        self.assertEqual((expectedMessage,), loggedMessages[0]['message']) 
Example #4
Source File: test_annotations.py    From attrs with MIT License 6 votes vote down vote up
def test_annotations_strings(self, slots, classvar):
        """
        String annotations are passed into __init__ as is.
        """

        @attr.s(auto_attribs=True, slots=slots)
        class C:
            cls_var: classvar + "[int]" = 23
            a: "int"
            x: "typing.List[int]" = attr.Factory(list)
            y: "int" = 2
            z: "int" = attr.ib(default=3)
            foo: "typing.Any" = None

        assert C.__init__.__annotations__ == {
            "a": "int",
            "x": "typing.List[int]",
            "y": "int",
            "z": "int",
            "foo": "typing.Any",
            "return": None,
        } 
Example #5
Source File: secrets.py    From environ-config with Apache License 2.0 6 votes vote down vote up
def _get(self, environ, metadata, prefix, name):
        ce = metadata[CNF_KEY]

        if ce.name is not None:
            var = ce.name
        else:
            if callable(self.vault_prefix):
                vp = self.vault_prefix(environ)
            else:
                vp = self.vault_prefix
            var = "_".join(((vp,) + prefix + (name,))).upper()

        log.debug("looking for env var '%s'." % (var,))
        val = environ.get(
            var,
            (
                attr.NOTHING
                if isinstance(ce.default, attr.Factory)
                else ce.default
            ),
        )
        if val is RAISE:
            raise MissingSecretError(var)
        return _SecretStr(val) 
Example #6
Source File: test_secrets.py    From environ-config with Apache License 2.0 6 votes vote down vote up
def test_default_factory(self, ini):
        """
        Defaults are used iff the key is missing.
        """

        def getpass():
            return "thesecret"

        @environ.config
        class Cfg(object):
            password = ini.secret(default=attr.Factory(getpass))
            secret = ini.secret(default=attr.Factory(getpass))

        cfg = environ.to_config(Cfg, {})

        assert Cfg("foobar", "thesecret") == cfg 
Example #7
Source File: test_make.py    From attrs with MIT License 6 votes vote down vote up
def test_factory_takes_self(self):
        """
        If takes_self on factories is True, self is passed.
        """
        C = make_class(
            "C",
            {
                "x": attr.ib(
                    default=Factory((lambda self: self), takes_self=True)
                )
            },
        )

        i = C()

        assert i is i.x 
Example #8
Source File: test_make.py    From attrs with MIT License 6 votes vote down vote up
def test_adds_keyword_only_arguments(self):
        """
        Attributes can be added as keyword-only.
        """

        @attr.s
        class C:
            a = attr.ib()
            b = attr.ib(default=2, kw_only=True)
            c = attr.ib(kw_only=True)
            d = attr.ib(default=attr.Factory(lambda: 4), kw_only=True)

        c = C(1, c=3)

        assert c.a == 1
        assert c.b == 2
        assert c.c == 3
        assert c.d == 4 
Example #9
Source File: test_dict_generation.py    From cattrs with MIT License 5 votes vote down vote up
def test_nodefs_generated_unstructuring_cl(converter, cl_and_vals):
    """Test omitting default values on a per-class basis."""
    cl, vals = cl_and_vals

    for attr, val in zip(cl.__attrs_attrs__, vals):
        if attr.default is not NOTHING:
            break
    else:
        assume(False)

    converter.register_unstructure_hook(
        cl, make_dict_unstructure_fn(cl, converter, omit_if_default=True)
    )

    inst = cl(*vals)

    res = converter.unstructure(inst)

    for attr, val in zip(cl.__attrs_attrs__, vals):
        if attr.default is not NOTHING:
            if not isinstance(attr.default, Factory):
                if val == attr.default:
                    assert attr.name not in res
                else:
                    assert attr.name in res
            else:
                if val == attr.default.factory():
                    assert attr.name not in res
                else:
                    assert attr.name in res 
Example #10
Source File: attrs.py    From prettyprinter with MIT License 5 votes vote down vote up
def pretty_attrs(value, ctx):
    cls = type(value)
    attributes = cls.__attrs_attrs__

    kwargs = []
    for attribute in attributes:
        if not attribute.repr:
            continue

        display_attr = False
        if attribute.default == NOTHING:
            display_attr = True
        elif isinstance(attribute.default, Factory):
            default_value = (
                attribute.default.factory(value)
                if attribute.default.takes_self
                else attribute.default.factory()
            )
            if default_value != getattr(value, attribute.name):
                display_attr = True
        else:
            if attribute.default != getattr(value, attribute.name):
                display_attr = True

        if display_attr:
            kwargs.append((attribute.name, getattr(value, attribute.name)))

    return pretty_call_alt(ctx, cls, kwargs=kwargs) 
Example #11
Source File: _environ_config.py    From environ-config with Apache License 2.0 5 votes vote down vote up
def to_config(config_cls, environ=os.environ):
    """
    Load the configuration as declared by *config_cls* from *environ*.

    :param config_cls: The configuration class to fill.
    :param dict environ: Source of the configuration.  `os.environ` by default.

    :returns: An instance of *config_cls*.

    This is equivalent to calling ``config_cls.from_environ()``.
    """
    if config_cls._prefix:
        app_prefix = (config_cls._prefix,)
    else:
        app_prefix = ()

    def default_get(environ, metadata, prefix, name):
        ce = metadata[CNF_KEY]
        if ce.name is not None:
            var = ce.name
        else:
            var = ("_".join(app_prefix + prefix + (name,))).upper()

        log.debug("looking for env var '%s'." % (var,))
        val = environ.get(
            var,
            (
                attr.NOTHING
                if isinstance(ce.default, attr.Factory)
                else ce.default
            ),
        )
        if val is RAISE:
            raise MissingEnvValueError(var)
        return val

    return _to_config(config_cls, default_get, environ, ()) 
Example #12
Source File: test_class_to_config.py    From environ-config with Apache License 2.0 5 votes vote down vote up
def test_factory_default():
    """
    Class based ``from_environ`` allows ``attr.Factory`` defaults.
    """

    @environ.config()
    class FactoryConfig(object):
        x = environ.var(attr.Factory(list))
        y = environ.var("bar")

    cfg = FactoryConfig.from_environ({"APP_Y": "baz"})

    assert cfg.x == []
    assert cfg.y == "baz" 
Example #13
Source File: tcp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _connectDone(self):
        """
        This is a hook for when a connection attempt has succeeded.

        Here, we build the protocol from the
        L{twisted.internet.protocol.ClientFactory} that was passed in, compute
        a log string, begin reading so as to send traffic to the newly built
        protocol, and finally hook up the protocol itself.

        This hook is overridden by L{ssl.Client} to initiate the TLS protocol.
        """
        self.protocol = self.connector.buildProtocol(self.getPeer())
        self.connected = 1
        logPrefix = self._getLogPrefix(self.protocol)
        self.logstr = "%s,client" % logPrefix
        if self.protocol is None:
            # Factory.buildProtocol is allowed to return None.  In that case,
            # make up a protocol to satisfy the rest of the implementation;
            # connectionLost is going to be called on something, for example.
            # This is easier than adding special case support for a None
            # protocol throughout the rest of the transport implementation.
            self.protocol = Protocol()
            # But dispose of the connection quickly.
            self.loseConnection()
        else:
            self.startReading()
            self.protocol.makeConnection(self) 
Example #14
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
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) 
Example #15
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def just_class_with_type(tup):
    nested_cl = tup[1][0]
    default = attr.Factory(nested_cl)
    combined_attrs = list(tup[0])
    combined_attrs.append(
        (attr.ib(default=default, type=nested_cl), st.just(nested_cl()))
    )
    return _create_hyp_class(combined_attrs) 
Example #16
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def list_of_class(tup):
    nested_cl = tup[1][0]
    default = attr.Factory(lambda: [nested_cl()])
    combined_attrs = list(tup[0])
    combined_attrs.append((attr.ib(default=default), st.just([nested_cl()])))
    return _create_hyp_class(combined_attrs) 
Example #17
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
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) 
Example #18
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
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) 
Example #19
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
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) 
Example #20
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
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) 
Example #21
Source File: test_functional.py    From attrs with MIT License 5 votes vote down vote up
def test_fields(self, cls):
        """
        `attr.fields` works.
        """
        assert (
            Attribute(
                name="x",
                default=foo,
                validator=None,
                repr=True,
                cmp=None,
                eq=True,
                order=True,
                hash=None,
                init=True,
                inherited=False,
            ),
            Attribute(
                name="y",
                default=attr.Factory(list),
                validator=None,
                repr=True,
                cmp=None,
                eq=True,
                order=True,
                hash=None,
                init=True,
                inherited=False,
            ),
        ) == attr.fields(cls) 
Example #22
Source File: test_tcp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_userFail(self):
        """
        Calling L{IConnector.stopConnecting} in C{Factory.startedConnecting}
        results in C{Factory.clientConnectionFailed} being called with
        L{error.UserError} as the reason.
        """
        serverFactory = MyServerFactory()
        reactor = self.buildReactor()
        tcpPort = reactor.listenTCP(0, serverFactory, interface=self.interface)
        portNumber = tcpPort.getHost().port

        fatalErrors = []

        def startedConnecting(connector):
            try:
                connector.stopConnecting()
            except Exception:
                fatalErrors.append(Failure())
                reactor.stop()

        clientFactory = ClientStartStopFactory()
        clientFactory.startedConnecting = startedConnecting

        clientFactory.whenStopped.addBoth(lambda _: reactor.stop())

        reactor.callWhenRunning(lambda: reactor.connectTCP(self.interface,
                                                           portNumber,
                                                           clientFactory))

        self.runReactor(reactor)

        if fatalErrors:
            self.fail(fatalErrors[0].getTraceback())
        clientFactory.reason.trap(UserError)
        self.assertEqual(clientFactory.failed, 1) 
Example #23
Source File: test_tcp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_reconnect(self):
        """
        Calling L{IConnector.connect} in C{Factory.clientConnectionLost} causes
        a new connection attempt to be made.
        """
        serverFactory = ClosingFactory()
        reactor = self.buildReactor()
        tcpPort = reactor.listenTCP(0, serverFactory, interface=self.interface)
        serverFactory.port = tcpPort
        portNumber = tcpPort.getHost().port

        clientFactory = MyClientFactory()

        def clientConnectionLost(connector, reason):
            connector.connect()
        clientFactory.clientConnectionLost = clientConnectionLost
        reactor.connectTCP(self.interface, portNumber, clientFactory)

        protocolMadeAndClosed = []
        def reconnectFailed(ignored):
            p = clientFactory.protocol
            protocolMadeAndClosed.append((p.made, p.closed))
            reactor.stop()

        clientFactory.failDeferred.addCallback(reconnectFailed)

        self.runReactor(reactor)

        clientFactory.reason.trap(ConnectionRefusedError)
        self.assertEqual(protocolMadeAndClosed, [(1, 1)]) 
Example #24
Source File: containers.py    From python-songpal with GNU General Public License v3.0 5 votes vote down vote up
def make(cls, **kwargs):
    """Create a container.

    Reports extra keys as well as missing ones.
    Thanks to habnabit for the idea!
    """
    cls_attrs = {f.name: f for f in attr.fields(cls)}

    unknown = {k: v for k, v in kwargs.items() if k not in cls_attrs}
    if len(unknown) > 0:
        _LOGGER.debug(
            "Got unknowns for %s: %s - please create an issue!", cls.__name__, unknown
        )

    missing = [k for k in cls_attrs if k not in kwargs]

    data = {k: v for k, v in kwargs.items() if k in cls_attrs}

    # initialize missing values to avoid passing default=None
    # for the attrs attribute definitions
    for m in missing:
        default = cls_attrs[m].default
        if isinstance(default, attr.Factory):
            if not default.takes_self:
                data[m] = default.factory()
            else:
                raise NotImplementedError
        else:
            _LOGGER.debug("Missing key %s with no default for %s", m, cls.__name__)
            data[m] = None

    # initialize and store raw data for debug purposes
    inst = cls(**data)
    setattr(inst, "raw", kwargs)

    return inst 
Example #25
Source File: fields.py    From reobject with Apache License 2.0 5 votes vote down vote up
def Field(*args, default=attr.NOTHING, **kwargs):
    if callable(default):
        default = attr.Factory(default)

    return attr.ib(*args, default=default, **kwargs) 
Example #26
Source File: test_make.py    From attrs with MIT License 5 votes vote down vote up
def test_default_decorator_sets(self):
        """
        Decorator wraps the method in a Factory with pass_self=True and sets
        the default.
        """
        a = attr.ib()

        @a.default
        def f(self):
            pass

        assert Factory(f, True) == a._default 
Example #27
Source File: test_make.py    From attrs with MIT License 5 votes vote down vote up
def test_factory_sugar(self):
        """
        Passing factory=f is syntactic sugar for passing default=Factory(f).
        """

        @attr.s
        class C(object):
            x = attr.ib(factory=list)

        assert Factory(list) == attr.fields(C).x.default 
Example #28
Source File: test_make.py    From attrs with MIT License 5 votes vote down vote up
def test_sugar_factory_mutex(self):
        """
        Passing both default and factory raises ValueError.
        """
        with pytest.raises(ValueError, match="mutually exclusive"):

            @attr.s
            class C(object):
                x = attr.ib(factory=list, default=Factory(list)) 
Example #29
Source File: test_make.py    From attrs with MIT License 5 votes vote down vote up
def test_sugar_callable(self):
        """
        Factory has to be a callable to prevent people from passing Factory
        into it.
        """
        with pytest.raises(ValueError, match="must be a callable"):

            @attr.s
            class C(object):
                x = attr.ib(factory=Factory(list)) 
Example #30
Source File: test_make.py    From attrs with MIT License 5 votes vote down vote up
def test_factory_hashable(self):
        """
        Factory is hashable.
        """
        assert hash(Factory(None, False)) == hash(Factory(None, False))