37

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?

0

1 Answer 1

59

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.