Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Class "Constants" in Dataclasses

Understanding that the below are not true constants, attempting to follow PEP 8 I'd like to make a "constant" in my @dataclass in Python 3.7.

@dataclass
class MyClass:
    data: DataFrame

    SEED = 8675309  # Jenny's Constant

My code used to be:

class MyClass:
    SEED = 8675309  # Jenny's Constant

    def __init__(data):
        self.data = data

Are these two equivalent in there handling of the seed? Is the seed now part of the init/eq/hash? Is there a preferred style for these constants?

like image 281
rhaskett Avatar asked Jan 24 '20 22:01

rhaskett


Video Answer


1 Answers

They are the same. dataclass ignores unannotated variables when determining what to use to generate __init__ et al. SEED is just an unhinted class attribute.

If you want to provide a type hint for a class attribute, you use typing.ClassVar to specify the type, so that dataclass won't mistake it for an instance attribute.

from dataclasses import dataclass
from typing import ClassVar


@dataclass
class MyClass:
    data: DataFrame
    SEED: ClassVar[int] = 8675309
like image 101
chepner Avatar answered Sep 20 '22 14:09

chepner