Python attr.Attribute() Examples

The following are 17 code examples of attr.Attribute(). 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: formatting.py    From xarray-simlab with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_attribute_section(process, placeholder="{{attributes}}"):
    data_type = ":class:`attr.Attribute`"

    fmt_vars = []

    for vname, var in variables_dict(process).items():
        var_header = f"{vname} : {data_type}"
        var_content = textwrap.indent(var_details(var, max_line_length=62), " " * 4)

        fmt_vars.append(f"{var_header}\n{var_content}")

    fmt_section = textwrap.indent(
        "Attributes\n" "----------\n" + "\n".join(fmt_vars), " " * 4
    )

    current_doc = process.__doc__ or ""

    if placeholder in current_doc:
        new_doc = current_doc.replace(placeholder, fmt_section[4:])
    else:
        new_doc = f"{current_doc.rstrip()}\n\n{fmt_section}\n"

    return new_doc 
Example #2
Source File: ui_settings.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def _nav_hover_text_color_validator(
        self, _: "attr.Attribute[Optional[str]]", value: Optional[str]
    ) -> None:
        if value is not None and not HEX_COLOR_REGEX.match(value):
            raise ValueError("nav_hover_text_color must be valid HEX color") 
Example #3
Source File: test_utils.py    From xarray-simlab with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_variables_dict():
    assert all(
        [
            isinstance(var, attr.Attribute)
            for var in utils.variables_dict(ExampleProcess).values()
        ]
    )

    assert "other_attrib" not in utils.variables_dict(ExampleProcess) 
Example #4
Source File: test_formatting.py    From xarray-simlab with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_add_attribute_section():
    # For testing, autodoc is set to False to avoid redundancy
    expected = """My process

    Attributes
    ----------
    var1 : :class:`attr.Attribute`
        A variable

        Variable properties:

        - type : ``variable``
        - intent : ``in``
        - dimensions : ('x',)

    var2 : :class:`attr.Attribute`
        No description given

        Variable properties:

        - type : ``variable``
        - intent : ``in``
        - dimensions : ()
    """

    assert add_attribute_section(WithoutPlaceHolder).strip() == expected.strip()
    assert add_attribute_section(WithPlaceholder).strip() == expected.strip() 
Example #5
Source File: config.py    From corrscope with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_units(field: attr.Attribute) -> str:
    return field.metadata.get(UNIT_SUFFIX, "") 
Example #6
Source File: utils.py    From attrs with MIT License 5 votes vote down vote up
def simple_attr(
    name,
    default=NOTHING,
    validator=None,
    repr=True,
    eq=True,
    hash=None,
    init=True,
    converter=None,
    kw_only=False,
    inherited=False,
):
    """
    Return an attribute with a name and no other bells and whistles.
    """
    return Attribute(
        name=name,
        default=default,
        validator=validator,
        repr=repr,
        cmp=None,
        eq=eq,
        hash=hash,
        init=init,
        converter=converter,
        kw_only=kw_only,
        inherited=inherited,
    ) 
Example #7
Source File: attrs.py    From marshmallow-annotations with MIT License 5 votes vote down vote up
def _get_attr_from_attrs(attrs: Iterable[Attribute], name: str) -> Attribute:
    attrs = [a for a in attrs if a.name == name]
    return attrs[0] 
Example #8
Source File: ui_settings.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def _nav_accent_color_validator(
        self, _: "attr.Attribute[Optional[str]]", value: Optional[str]
    ) -> None:
        if value is not None and not HEX_COLOR_REGEX.match(value):
            raise ValueError("nav_accent_color must be valid HEX color") 
Example #9
Source File: utils.py    From pycoalaip with Apache License 2.0 5 votes vote down vote up
def __setattr__(self, name, value):
        """Mimic attr.s(frozen=True) behaviour but allow for attributes
        to be initialized after class instantiation.

        Useful when you would like a class to be immutable after a
        certain action, such as a save to a database.

        Any attributes created with ``attr.ib(init=False)`` or are
        initially set to ``None`` in ``__init__()`` are allowed to have
        their values be set once after initialization. Any other
        attributes with initial values set are immediately frozen upon
        initialization.

        **Note**: Obviously, this doesn't stop anyone from setting the
        uninitialized attributes before you've set it yourself.
        Hopefully, you've got responsibile users.

        Raises:
            :class:`attr.exceptions.FronzenInstanceError`: if a frozen
                attribute is set
        """
        current_value = getattr(self, name, None)
        if current_value is None or isinstance(current_value, attr.Attribute):
            super().__setattr__(name, value)
        else:
            raise attr.exceptions.FrozenInstanceError() 
Example #10
Source File: ui_settings.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def _nav_hover_bg_color_validator(
        self, _: "attr.Attribute[Optional[str]]", value: Optional[str]
    ) -> None:
        if value is not None and not HEX_COLOR_REGEX.match(value):
            raise ValueError("nav_hover_bg_color must be valid HEX color") 
Example #11
Source File: ui_settings.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def _nav_bg_color_validator(
        self, _: "attr.Attribute[Optional[str]]", value: Optional[str]
    ) -> None:
        if value is not None and not HEX_COLOR_REGEX.match(value):
            raise ValueError("nav_bg_color must be valid HEX color") 
Example #12
Source File: ui_settings.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def _text_color_validator(self, _: "attr.Attribute[str]", value: str) -> None:
        if not HEX_COLOR_REGEX.match(value):
            raise ValueError("text_color must be valid HEX color")

    # noinspection PyUnresolvedReferences 
Example #13
Source File: ui_settings.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def _bg_color_validator(self, _: "attr.Attribute[str]", value: str) -> None:
        if not HEX_COLOR_REGEX.match(value):
            raise ValueError("bg_color must be valid HEX color")

    # noinspection PyUnresolvedReferences 
Example #14
Source File: ui_settings.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def _json_sample_expand_level_validator(
        self, _: "attr.Attribute[Union[int, str]]", value: Union[int, str]
    ) -> None:
        if isinstance(value, str) and value != "all":
            raise ValueError(
                f"jsonSampleExpandLevel must be either 'all' or integer, got '{value}'"
            ) 
Example #15
Source File: ui_settings.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def _expand_responses_validator(self, _: "attr.Attribute[str]", value: str) -> None:
        if value in ("all", ""):
            return
        raw_codes = value.split(",")
        for raw_code in raw_codes:
            try:
                int(raw_code)
            except ValueError:
                raise ValueError(
                    "expandResponses must be either 'all' or "
                    f"comma-separated list of http codes, got '{raw_code}'"
                )

    # noinspection PyUnresolvedReferences 
Example #16
Source File: test_validators.py    From grafanalib with Apache License 2.0 5 votes vote down vote up
def create_attribute():
    return attr.Attribute(
        name='x',
        default=None,
        validator=None,
        repr=True,
        cmp=None,
        eq=True,
        order=False,
        hash=True,
        init=True) 
Example #17
Source File: process.py    From xarray-simlab with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def filter_variables(process, var_type=None, intent=None, group=None, func=None):
    """Filter the variables declared in a process.

    Parameters
    ----------
    process : object or class
        Process class or object.
    var_type : {'variable', 'on_demand', 'foreign', 'group'}, optional
        Return only variables of a specified type.
    intent : {'in', 'out', 'inout'}, optional
        Return only input, output or input/output variables.
    group : str, optional
        Return only variables that belong to a given group.
    func : callable, optional
        A callable that takes a variable (i.e., a :class:`attr.Attribute`
        object) as input and return True or False. Useful for more advanced
        filtering.

    Returns
    -------
    attributes : dict
        A dictionary of variable names as keys and :class:`attr.Attribute`
        objects as values.

    """
    process_cls = get_process_cls(process)

    # be consistent and always return a dict (not OrderedDict) when no filter
    vars = dict(variables_dict(process_cls))

    if var_type is not None:
        vars = {
            k: v
            for k, v in vars.items()
            if v.metadata.get("var_type") == VarType(var_type)
        }

    if intent is not None:
        vars = {
            k: v
            for k, v in vars.items()
            if v.metadata.get("intent") == VarIntent(intent)
        }

    if group is not None:
        vars = {k: v for k, v in vars.items() if group in v.metadata.get("groups", [])}

    if func is not None:
        vars = {k: v for k, v in vars.items() if func(v)}

    return vars