Skip to main content

Questions tagged [python-attrs]

Use for questions about the third-party Python library for data classes

python-attrs
0 votes
1 answer
72 views

How to implement class composition

Hi I have a model that contain several items, now all of the items have a set of shared properties: id, name, parent. In addition some of this items are meant only to contain other items. Some are ...
Al_'s user avatar
  • 1
0 votes
0 answers
18 views

Pylint warnings with attrs

I keep getting warnings from pylint while trying to iterate over an attribute in a class that uses the attrs package. from typing import List from attrs import define, Factory @define class MyClass: ...
Al_'s user avatar
  • 1
0 votes
0 answers
21 views

Is it possible to utilize a lambda function in an python-attrs converter? [duplicate]

I am attempting to automatically create converter functions that require metadata to operate. I am seeing odd behavior when a lambda function is used for the converter. import attrs def add(x, y=10): ...
slaughter98's user avatar
  • 1,853
1 vote
1 answer
60 views

In python Attrs package, how to add a field in the field_transformer function?

The documentation for the python Attrs, the Automatic Field Transformation and Modification section states ...You can add converters, change types, and even remove attributes completely or create new ...
slaughter98's user avatar
  • 1,853
0 votes
1 answer
329 views

Pyright cause reportAttributeAccessIssue on attrs validator

Environment Python v3.9.13 Pyright 1.1.357 attrs 23.1.0 The code at official document of attrs library make the pyright type checker casue reportAttributeAccessIssue https://www.attrs.org/en/stable/...
usan's user avatar
  • 103
0 votes
0 answers
22 views

Interlinked validators using python attrs

I want to use attrs to run validators on values inside my class. Here is an example: from attrs import define, field @define(kw_only=True) class Foo: x: float = field() min_x: float = field() ...
Mike's user avatar
  • 155
0 votes
1 answer
61 views

Set defaults for attrs subclass that uses validators from parent class?

Consider this minimal example: from attrs import define, field, validators @define(kw_only=True) class Vehicle: num_wheels: int = field(validator=validators.instance_of(int)) @num_wheels....
Mike's user avatar
  • 155
0 votes
1 answer
42 views

Unexpected `FrozenInstanceError` in unit test when using a frozen exception

I have a unit test that I want to show failing as part of a bug report. It's important not only that the test fail with an error, but that the error message very clearly evidences the underlying bug. ...
ApproachingDarknessFish's user avatar
0 votes
1 answer
144 views

How do you get cattrs to unstructure nested structures?

In Python, with the libraries attrs and cattrs, I have a nested structure defined as follows: @attrs.define class Score: added: datetime value: float @attrs.define class Entry: score: ...
Matt's user avatar
  • 9,958
1 vote
0 answers
56 views

How do I set parameters of objects saved in a list class without looping?

I have 1 main class and one class, that functions as a storage list for every object created, so I can keep track of every newly created user. But how can I access the parameters of a user in that ...
Kiri's user avatar
  • 9
1 vote
1 answer
86 views

Pylance doesn't recognize attrs.field with converters

Pylance seems to recognize an attrs field as a function (rather than a variable) when the paramter converter= is specified. Am I doing right and how to correct it? (Python v3.8.13, Pylance v2023.12....
Chitaoji's user avatar
1 vote
1 answer
216 views

mypy doesn't recognize the latest version of attrs?

Is some special setup needed to help mypy recognize standard attrs usage? somefile.py:7: error: Cannot find implementation or library stub for module named "attr" [import-not-found] (...
Y123's user avatar
  • 967
2 votes
2 answers
105 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' ...
brillenheini's user avatar
0 votes
1 answer
129 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 ...
shridhar singh's user avatar
0 votes
1 answer
52 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 ...
Gabe's user avatar
  • 42
2 votes
2 answers
256 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. ...
Jan's user avatar
  • 425
0 votes
0 answers
114 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 ...
InSync's user avatar
  • 8,619
0 votes
1 answer
128 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 ...
The unknown's user avatar
0 votes
0 answers
58 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 ...
The unknown's user avatar
1 vote
2 answers
367 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, ...
baxx's user avatar
  • 4,338
1 vote
2 answers
440 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(...
Wör Du Schnaffzig's user avatar
4 votes
1 answer
769 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 ...
Danosaurus's user avatar
2 votes
2 answers
457 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 ...
Tom Close's user avatar
  • 574
1 vote
1 answer
471 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 ...
Fragan's user avatar
  • 852
1 vote
1 answer
464 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 ...
Floh's user avatar
  • 839
1 vote
2 answers
88 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 ...
user11429634's user avatar
0 votes
1 answer
230 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 ...
Wör Du Schnaffzig's user avatar
2 votes
1 answer
579 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 ...
GlaceCelery's user avatar
  • 1,013
1 vote
1 answer
52 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 = ...
structuralengin's user avatar
0 votes
1 answer
93 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 ...
roulette01's user avatar
  • 2,344
1 vote
1 answer
758 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( **...
user19007114's user avatar
0 votes
2 answers
466 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 ...
waszil's user avatar
  • 460
0 votes
1 answer
392 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 ...
M4urice's user avatar
  • 621
0 votes
1 answer
832 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 ...
devKanapka's user avatar
0 votes
1 answer
734 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 ...
SimonT's user avatar
  • 1,019
4 votes
1 answer
2k 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), ...
VaNa's user avatar
  • 361
0 votes
0 answers
32 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(...
Miguel Andrade's user avatar
1 vote
1 answer
531 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 ...
Pierre Brasseau's user avatar
1 vote
0 answers
275 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 ...
hamnghi's user avatar
  • 99
1 vote
1 answer
159 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 ...
Orange Chen's user avatar
4 votes
2 answers
491 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"]) ...
Elia's user avatar
  • 802
0 votes
0 answers
245 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 ...
brillenheini's user avatar
0 votes
2 answers
544 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 ...
Guy's user avatar
  • 355
-1 votes
2 answers
54 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: ...
Чёткая ворона's user avatar
0 votes
0 answers
321 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: :...
OrenIshShalom's user avatar
0 votes
1 answer
52 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: ...
OneRaynyDay's user avatar
  • 3,828
0 votes
2 answers
403 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 ...
user18140022's user avatar
0 votes
1 answer
292 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 ...
Chaban33's user avatar
  • 1,372
1 vote
2 answers
482 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 ...
OrenIshShalom's user avatar
1 vote
2 answers
356 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 ...
talz's user avatar
  • 1,140

15 30 50 per page