What is attrs?

Attrs stands for “attribute” in general. We’ll look at using this function in Python, and CSS in this article.

Attrs in Python

Attrs is a Python module that relieves you of the labour of implementing object protocols, allowing you to return to the delight of developing classes (aka dunder methods). Its major purpose is to enable you to build concise and accurate software without slowing down your code, and NASA has trusted it for Mars missions since 2020.

The attrs package is intended to assist Python programmers in maintaining clean and speedy code. Designers are used to changing the Python classes __slots__ and __init__functionality. Having worked with Python classes before, __init__ is simple. On the other hand, __slots__ is difficult. Let’s give you an example. Assume you’re making a data-holding object:

The disadvantage of utilizing this class is that it derives from the object class; therefore, we’re producing entire objects with wasted memory when we use it. All properties are stored in regular Python objects’ __dict__ attribute.

This allows you to keep as many properties as you want, but it has the disadvantage of being memory-intensive because you must store the object, its keys, value references, etc. You may use __slots__ to inform Python which attributes are exclusively permitted for a certain class.

This saves Python a lot of time to ensure that new properties can be added. To be efficient, namedtuple accomplishes this behind the scenes. If we want the x and y attributes in our Point class example, we set __slots__ to a tuple of attribute strings. Python will produce an error if we try to put any additional characteristics with this configuration.

So, what does attrslibrary have to do with any of this? The attrs library, on the other hand, takes care of all of this boilerplate, as well as a few other features, for you. We can make lightweight objects using attrs as we did with __slots__.

The attr.s class decorator and the attr.ib function are the two functions we’ll look at. The Python class may be turned into a __slots__ based object using attr.s. Then we use attr.ib to define attributes. The Point mentioned above class may be rewritten as:

To make this class even easier, we may supply a variety of parameters to attr.ib. When using the kw only option, you are only allowed to provide keyword arguments when instantiating the class.

If no value is supplied for an argument, the default argument sets a default value. We may also specify a converter parameter to immediately convert the incoming value of an argument.

If no value is handed in, the class will convert both x and y to integers and set the default to 0. The y parameter must also be given as a keyword argument. x=0 and y=2 will be set by point(y=2).

We can also use @attr.s(kw only=True) to force this setting on all attributes by passing kw only=True to attr.s. It’s a little tough to figure out what the default value is. We can utilize immutable built-in Python types like str and int, but we must use the attr.

Factory method to employ mutable types. Using x = attr.ib(default=[]) as a class attribute will set x for all instances produced. Demo.foo uses a shared list object in this example, but demo.bar does not because new class objects do not exchange values:

We may also use the attrs library to convert data. By default, the __repr__ function displays all of a class’s attributes.

Instead of the cryptic< __main__, printing the object returns usPoint(x=1, y=2). Object should be pointed at 0x104bac5f7>. We can also use attr.asdict to transform an object into a dict by passing in an attr-based class. ‘x’: 1, ‘y’: 2′ will be returned by attr.asdict(p). We may also use attr.s(frozen=True) to make all attributes unchangeable.

There are a few more lesser-known attr functions, but validators is one we’d want to discuss. For properties provided in a class, we may define custom validators. If x is more than 5, the code will throw a ValueError during class creation.

Attrs in CSS

The normal relationship between CSS and HTML is that CSS selectors match HTML components, and CSS styles them. CSS is completely unaware of the HTML text. However, there is a way for CSS to access data in HTML if the data is included within an attribute on the HTML element.

It goes somewhat like this:

That’s intriguing. For example, you could use it to make (very inaccessible) tooltips; the HTML code would be:

The CSS code for this will be as follows:

However, because HTML cannot be used in the property value, such tooltips are confined to a string value and cannot contain a title, link, or anything else.

Here’s an example of more appropriate use. There’s an old print stylesheet trick that involves using attr() to add URLs to links so you can see what they’re pointing to:

That’s a clever idea. But what else is there? Could you please pass a colour down to me?

That isn’t incorrect, but it isn’t helpful.

A string is returned by attr(). Even though the string has the same format as a hex code, it will not be utilized as one.

You can’t even give a URL that can be utilized in a background-image element (). You cannot pass a unit such as 3, 20px, 4rem, or 0.8vw.

Let’s remember that the attr() method in CSS only works with strings, and strings are only truly helpful as content (due to the fact that it’s unselectable and somewhat inaccessible).

When should you utilize attrs?

The shape and values are the focus of attrs. If you’re looking for a unique way to express yourself, try using attrs:

You want to ensure that the values you’ve entered are correct. The equivalent of a ChoiceField is a popular example.

  • When you wish to clean or normalize the data.
  • If you want a higher level of formalization, than dataclasses alone can provide
  • When you’re anxious about your memory and ability to execute. Attrs may be used to build slotted classes, which CPython will optimize.

It’s always simpler to start with dataclasses and then transition to attr.s if your needs evolve or you find you need to protect against a certain value. That’s a common occurrence in software development, and it’s referred to as “continuous refactoring” by developers.

Leave a Comment