#π AI is leaning towards dataclasses. Would appreciate a little lesson
69 messages Β· Page 1 of 1 (latest)
@calm mortar
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
I would appreciate at least a bit of information regarding to dataclasses if not actual coding guidance.
The current codebase in case interested: https://github.com/Kuba-Kowal/Passive-DNS-Recon-Tool
do you know about class?
A dataclass is really mostly a convenience facility for providing a lot of the common boilerplate we make by hand.
class Foo:
def __init(self, a, b):
self.a = a
self.b = b
def __str__(self):
return f'Foo(a={self.a},b={self.b})'
and so on. The @dataclass decorator provides default versions of these things (you can override any of them still).
The other thing is that it lets you define the attributes with type annotations:
from dataclasses import dataclass
@dataclass
class FOO:
a : int
b : str
and also to provide factories for their default values (if a plain default value isn't enough).
!doc dataclasses
Source code: Lib/dataclasses.py
This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes. It was originally described in PEP 557.
The member variables to use in these generated methods are defined using PEP 526 type annotations. For example, this code...
if you want to dig a little bit deeper: https://realpython.com/python-data-classes/
!e
@dataclass
class User:
name: str
age: int
u = User("Alice", 30)
print(u)
:x: Your 3.14 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m1[0m, in [35m<module>[0m
003 | @[1;31mdataclass[0m
004 | [1;31m^^^^^^^^^[0m
005 | [1;35mNameError[0m: [35mname 'dataclass' is not defined[0m
!e
from dataclass import dataclass
@dataclass
class User:
name: str
age: int
u = User("Alice", 30)
print(u)
:x: Your 3.14 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m1[0m, in [35m<module>[0m
003 | from dataclass import dataclass
004 | [1;35mModuleNotFoundError[0m: [35mNo module named 'dataclass'[0m
from dataclasses import dataclass
not
from dataclass import dataclass
!e
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
u = User("Alice", 30)
print(u)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
User(name='Alice', age=30)
!e
from dataclasses import dataclass
@dataclass
class User(slots=True):
name: str
age: int
u = User("Alice", 30)
print(u)
:x: Your 3.14 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m4[0m, in [35m<module>[0m
003 | class User(slots=True):
004 | name: str
005 | age: int
006 | [1;35mTypeError[0m: [35mUser.__init_subclass__() takes no keyword arguments[0m
!e
from dataclasses import dataclass
@dataclass(slots=True)
class User:
name: str
age: int
u = User("Alice", 30)
print(u)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
User(name='Alice', age=30)
would you be able to explain the difference in this?
i was just having a convo about it with the LLM
it means it doesnt return it as a dictionary
.
so it enforces declaration
so only the values i assigned when the object is created
are the values that can be utilised
but now thats caused even more confusion because i thought that is what frozen is for...
By default class instances store their data in a __dict__ dictionary. When you access attributes of the instances, it looks up the values from the dictionary.
With slots, the data is instead held in an array. This takes up less space, is faster to access, and prevents arbitrary members from being added.
is the array, an array of Slot=Value
or like an array of arrays
or simply every slot has its own array
When you enable slots, each instance attribute is an element of an array.
I'll link to the official high level documentation for general reference: https://docs.python.org/3/reference/datamodel.html#slots
almost like a preallocation of ram
0x01 = VariableX
0x02 = VariableY
when you use slots instead of, for key in dictionary if key = this
you just call 0x01
More like: imagine the attributes are not in a dict keyed by the attribute name, but in a list, where the first named attribute has position 0 and the second 1 and so on. The Python byte code knows to access that way in the list instead of by attribute name in a dict
ohh i see
The access is faster, your code is unchanged, but you can't use open ended arbitrary other attributes in that class
and this is memory efficient, because it involves preallcoation (high-level)
rather than dynamic or whatever
that also
though the memory for a dict vs list is usually well outstripped by the memory for whatever objects are on the attributes anyway
In both cases, you tend to "reallocate". Well written classes tend to initialize every member on creation. So it's more preallocating an array vs a dictionary.
with slots the array is a fixed size, no?
Yes. You'll get runtime errors if you try to add a member that wasn't included in __slots__.
slots are usually chosen (by the programmer) because you anticipate making many such objects; then the smaller memory footprint becomes relevant
yeah, the AI is recommending I utilise it for my large amounts of data I will be handling with this
appreciate the insight though guys
I don't know of any downside to using them. Having a closed set of members is usually a good choice anyway.
If you're making make many instances of the class yes.
If the class instances just have attributes which hold big things, it's not relevant.
would you say it provides additional security too?
yeah like one object per certificate
I'd say it prevents some kinds of accidents, like misspelling an attribut name or trying to use an attribute the class really doesn't support.
and per asn
Idk about "security", other than it can make some mistakes more obvious.
class MyClass:
def __init__(self):
self.my_attr = 1
inst = MyClass()
inst.my__attr = 2 # Ideally this should fail loudly, but happens silently
oh i see
That's an easy typo to make, and it not doing something obvious is not ideal. This is the kind of dumb thing that you pull your hair out over for a while because it superficially seems fine
*Typo'd that hard
!e
class MyClass:
__slots__ = ['my_attr']
def __init__(self):
self.my_attr = 1
inst = MyClass()
inst.my__attr = 2
:x: Your 3.14 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m8[0m, in [35m<module>[0m
003 | [1;31minst.my__attr[0m = 2
004 | [1;31m^^^^^^^^^^^^^[0m
005 | [1;35mAttributeError[0m: [35m'MyClass' object has no attribute 'my__attr' and no __dict__ for setting new attributes. Did you mean: 'my_attr'?[0m
Oh good. I haven't actually tested that in years lmao.
And it even gives a suggestion. Isn't that nice.
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.