Questions tagged [python-attrs]
Use for questions about the third-party Python library for data classes
148
questions
2
votes
2
answers
67
views
How to nest a list of attrs classes into an attrs class
I have a list of dicts and I'd like to use python-attrs to convert them into classes.
Here's the sample data:
[[characters]]
first_name = 'Duffy'
last_name = 'Duck'
[[characters]]
first_name = 'Bugs'
...
0
votes
1
answer
71
views
Using class methods to return instances and simply defining __init__(self, **kwargs):
One pattern I recently started using is writing class methods to return instances. In particular, I've been using it for dataclasses (with or without the @dataclass decorator). But it has also led me ...
0
votes
1
answer
38
views
Is there a way to access a class field as a property in python?
I've been trying to craft a small "mongodb orm" on top of pymongo with attrs. For this I've found that there's not a way for me to keep a consistent structure through the whole app since ...
2
votes
2
answers
89
views
How should I pass a class as an attribute to another class with attrs?
So, I just stumbled upon a hurdle concerning the use of attrs, which is quite new to me (I guess this also applies to dataclasses?). I have two classes, one I want to use as an attribute for another. ...
0
votes
0
answers
46
views
Using attrs decorators in PyCharm
I have the following attrs class:
from attrs import define, field
@define
class Foo:
bar: int = field()
@bar.validator
def check(self, attribute, value):
...
It works ...
0
votes
1
answer
44
views
How do you type hint a protocol with attrs.field?
I want to use attrs to use its ability evolve my class, hashing and more. But I would also like to use the protocol pattern. However since attrs does not do well with multiple inheritance, I am having ...
0
votes
0
answers
45
views
python redefining `attrs.field` to accept default argument
How do you redefine the attrs.field function (and type hint it) to accept a default argument? This is my current code.
from attrs import define, field
def fixed_attr(default, **kwargs):
return ...
0
votes
2
answers
99
views
How to mypy typehint an attrs validator attribute
Given the following:
from pathlib import Path
import attr
@attr.define(frozen=False)
class ExampleAtt:
x: str = attr.field()
@x.validator
def check(self, attribute: attr.Attribute, ...
0
votes
2
answers
96
views
Instantiate attrs class from dict with superfluous key/value pairs
I decorated a class using attrs.define and added all important attributes/fields.
import attrs
@attrs.define
class MyAttrsClass:
important1 = attrs.field(type = int)
important2 = attrs.field(...
3
votes
0
answers
213
views
SQLAlchemy typing support on filter for imperatively mapped attrs classes
For my application I am trying to separate my "domain layer" classes from the database backend, in order to be able to unit test these classes independently of the database. I use mypy for ...
2
votes
2
answers
180
views
How to type dynamically created classes so mypy can lint them properly
I'm looking to refactor the function task decorator of a dataflow engine I contribute to called Pydra so that the argument types can be linted with mypy. The code captures the arguments to be passed ...
1
vote
1
answer
207
views
Python attrs nested objects convertes
I'm using attrs lib to parse my configuration file, and I'm looking for a better way to parse nested data objects.
Example :
from attrs import define, field, validators
from typing import Dict
class ...
0
votes
1
answer
202
views
Using attrs is it ok to set init=False to an attribute with no default value
I use attrs library.
I use some attributes that are set by the __attrs_post_init__ method.
For them, I want to prevent them from being part of the constructor.
Is it ok to not put a default value, or ...
1
vote
2
answers
61
views
'NoneType' object has no attribute 'attrs' error in python
I am trying to scarp the the site: https://stackoverflow.com/questions/tagged/docusignapi to get vote_count, answers and views. However I am getting None values for few questions and not sure how to ...
0
votes
1
answer
108
views
Annotating function argument accepting an instance of a class decorated with @define
I'm using pythons attrs package to @define some classes containing some members with little logic for isolation purposes.
However, when I run the following stripped down example:
from attrs import ...
1
vote
1
answer
307
views
attrs - how to validate an instance of a Literal or None
This is what I have. I believe there are two problems here - the Literal and the None.
from attrs import frozen, field
from attrs.validators import instance_of
OK_ARGS = ['a', 'b']
@field
class ...
1
vote
1
answer
46
views
Inherited has no attribute X after using `attr`
The following snippet runs fine:
class base:
@classmethod
def func(cls):
cls.params
class inherited(base):
params = 2
def my_func(self):
inherited.func()
obj = ...
0
votes
1
answer
78
views
__init__() takes from 1 to 2 positional arguments but 4 were given after refactorizing class to be under base class
I have a class that currently looks something like this:
import attr
@attr.s
class my_class(object):
var1 = attr.ib(default=5)
var2 = attr.ib(default=5)
var3 = attr.ib(default=5)
@classmethod
...
1
vote
1
answer
406
views
cattrs.structure with nested dictionaries and attrs.define( converter=foo )
I am having issues structuring dicts, which contain invalid data, into @attrs.define decorated classes, but should be handled with attrs.define converters.
I have managed to get it to work with Foo( **...
0
votes
2
answers
199
views
python attrs inherited field value gets overwritten
I have some attrs classes that inherit from a base class. The parent class has a field that is also an attrs class.
If I instantiate two instances of the child classes and set the common inherited ...
0
votes
1
answer
293
views
How to customize attrs field hash
I'd like to use a Numpy array as a field value while keeping my attrs class hashable. For that purpose, I found joblib's hash() function to be a good means of hashing Numpy arrays. Is there any ...
0
votes
1
answer
424
views
How to annotate attrs field with validator?
I am having trouble annotating attrs class attribute.
I am using NewType for defining new UserId type and attrs frozen classes.
This is code where mypy doesn't complain and everything is alright:
from ...
0
votes
1
answer
473
views
Using cattrs / attrs where attr name does not match keys to create an object
I am looking at moving to cattrs / attrs from a completely manual process of typing out all my classes but need some help understanding how to achieve the following.
This is a single example but the ...
0
votes
1
answer
442
views
Is there an easy way to construct a pandas DataFrame from an Iterable of dataclass or attrs objects?
One can do that with dataclasses like so:
from dataclasses import dataclass
import pandas as pd
@dataclass
class MyDataClass:
i: int
s: str
df = pd.DataFrame([MyDataClass("a", 1), ...
0
votes
0
answers
26
views
Different objects are preserving the state using attrs
I'm making some experiments using attrs, but I'm experiencing some unexpected behaviors in the following code:
I created a class as this one:
@define
class User:
name = field()
errors = field(...
1
vote
1
answer
349
views
Serialising with cattrs and want to omit field x1 string field
Using cattrs to structure data and I want to omit x1 string field.
I want to perform a trivial cleanup on strings that have been passed in except for the password field.
I can get it to work on all ...
1
vote
0
answers
166
views
Add caching to __new__
I have a frozen class (decorated with attrs.frozen). However, the program might have to create many instances of that class. Since they are immutable and I only want to read from them, I want some ...
0
votes
1
answer
108
views
What happens exactly when a python class instance use dot to access attributes?
Suppose a class A is defined as:
class A:
def __init__(self, val):
self.val = val
After A is instantiated by a = A(3), what methods will be called by executing a.val? In other words, what ...
3
votes
2
answers
321
views
attrs convert list[str] to list[float]
Given the following scenario:
import attrs
@attrs.define(kw_only=True)
class A:
values: list[float] = attrs.field(converter=float)
A(values=["1.1", "2.2", "3.3"])
...
0
votes
0
answers
156
views
Type annotation in python-attrs
I'm going to use attrs for a class within my ETL process and currently I struggle with its type annotation capabilities.
For instance, I have this code:
@define(auto_attribs=True, kw_only=True)
class ...
0
votes
2
answers
321
views
How to override an attrs class instance with another one when the values are not None
My goal is to be able to merge multiple instances of the same attrs class and skip 'None' values.
This allows me to create default values and later override them when I need to.
An example of the ...
-1
votes
2
answers
52
views
Define custom atrributes in attr module
I'm looking for way, that I can define class attributes as I want.
For example, I tried this way:
@attrs.define
class MyClass:
pass
MyClass(a=1, b=2)
But recieving the TypeError:
TypeError: ...
0
votes
0
answers
258
views
Exclude all attrs auto-generated methods from sphinx
I have a simple attrs data class:
from attrs import frozen
@frozen
class Person
raw: str
I document it with the simplest *.rst file:
.. autoclass:: api.main.person.Person
:members:
:...
0
votes
1
answer
43
views
Correct mro order attrs object can't find abstract property
The following runs fine:
from abc import ABC, abstractmethod
import attr
class A(ABC):
@abstractmethod
def prop(self):
pass
def foo(self):
print(self.prop())
class B:
...
0
votes
2
answers
252
views
How can I specify order of fields in Attrs?
Taking from attrs example here but adding group_id & name. I want to create data classes so I can then export them to JSON using json.dump().
@define
class User:
email: str
password: str
...
0
votes
1
answer
201
views
frozen dataclass in def __init__ and iteration on it
I want to use a frozen class as a structure as I don't want to use any mutable objects in my code. But also I need to iterate on my_data. How can I make this work?
SideNote: dict is not an option
from ...
1
vote
2
answers
358
views
Passing parameters to frozen super dataclass
I have a simple (frozen) dataclass inheritance as follows:
from attrs import frozen
@frozen
class Interval:
left: str
right: str
@frozen
class RealInterval(Interval):
def ...
1
vote
2
answers
264
views
Attribute Converter in attr.s-based hydra Structured Configs
Is it possible to use converters in attr.s-based hydra-structured configs.
I tried it with this minimal example:
import hydra
from hydra.core.config_store import ConfigStore
import attr
@attr.s
class ...
3
votes
1
answer
544
views
How do I annotate an `attrs` validator function without breaking it?
Using the attrs library, I can define a validator for attribute values:
from attrs import define, field
def is_odd(inst, attr, value):
if value % 2 == 1:
return None
raise ValueError(...
0
votes
1
answer
151
views
frozen data class with non trivial constructor
I'm trying to define a frozen data class with a non-trivial constructor
That is, the constructor needs to "tweak" the input before it initializes the corresponding data member:
from attrs ...
1
vote
1
answer
368
views
Correct backwards-compatible way to migrate to modern attrs/cattrs style?
Question
I have a set of projects that I wrote starting in early 2020 using attrs v19.3.0 and cattrs for serialization/deserialization. What is the correct, fully backwards-compatible way to migrate ...
2
votes
1
answer
2k
views
Python attrs: Inheriting from class which values have default values raises error
I have a situation where attrs class inherits from another class which attributes have default value. This raises ValueError.
Here's an example:
from attrs import define
@define
class A:
a: int = ...
0
votes
1
answer
842
views
Create a customer converter and validator using ATTRS
I am trying to learn attrs and I have two questions. Please note that I am using the ATTRS library, not ATTR.
How do I create a converter to change typ to uppercase?
---> I solved this question. ...
2
votes
2
answers
1k
views
serializing to JSON an array of data classes
I have an array of data classes I need to serialize to JSON. I wrap the list in a class (Persons)
@attrs.frozen
class Person:
name: str
age: int
grades: Dict[str, int]
@attrs.define
class ...
2
votes
1
answer
513
views
Why can I not add attributes to an attrs object?
Consider this example:
import attrs
@attrs.define(frozen=True)
class A:
def __init__(self):
object.__setattr__(self, "field", 1)
A()
This fails with an exception:
...
0
votes
1
answer
61
views
With Python's attrs, is it possible to remove leading underscores from the generated __repr__
With my project that uses attrs, I'm defining some fields with a leading underscore so that I can make a property with the same name minus the leading underscore. I'm doing this because I'm adding ...
0
votes
2
answers
1k
views
How to define a class attribute by other attributes of the same class using "attrs"
I'm new with attrs module & I've encountered something that I didn't understand very well.
For simplicity I have this code below:
import attr
from typing import List
@attr.define
class A:
a: ...
1
vote
1
answer
162
views
Problem with initiating base with child class while working with python-attrs module
I'm trying to create Model class with attrs module. In my script CollectionModel class is inherited in User class. So logically all the attributes in the CollectionModel should be available in the ...
0
votes
1
answer
139
views
Different objects for the same class initiated with same value while working with attrs module
I'm trying to create Model class with attrs module. I'm generating iid value with bson ObjectId which returns a unique value with every call. And generating timestamp value with time module.
While I ...
0
votes
1
answer
94
views
How to invoke default methods with attrs python package
All,
Thank you for taking the time to try and address my question. My question is related to a specific Python package called attrs (https://www.attrs.org/en/stable/). I am just getting started with ...