0

I have just started using @dataclass decorator. This is my without dataclass implementation

class Myclass:

    def __init__(self, path: str = None, company_name: List = None):

        self.path = path
        self.company_name = company_name

        if path is not None:
            with open(self.path, 'r') as f:
                self.data = yaml.load(f, Loader=yaml.FullLoader)
        else:
            self.data = {'company': self.company_name}

So here, I am making an instance attribute assignment.

c = Myclass(path = '/home/akash/project/stock-analysis/data/sample_company.yaml')
c.data
>>>{'company': ['ADANIGREEN', 'HDFCAMC', 'WHIRLPOOL', 'APLAPOLLO', 'LALPATHLAB']}

The @dataclass equivalent which I manage is

@dataclass
class Myclass:
    path: str=None
    company_name: List=None
        
    def __post_init__(self):
        if self.path is not None:
            with open(self.path, 'r') as f:
                self.data = yaml.load(f, Loader=yaml.FullLoader)
        else:
            self.data = {'company': self.company_name}

It gives exactly the same output (which is expected)

c = Myclass(path = '/home/akash/project/stock-analysis/data/sample_company.yaml')
c.data
>>>{'company': ['ADANIGREEN', 'HDFCAMC', 'WHIRLPOOL', 'APLAPOLLO', 'LALPATHLAB']}

So, am I doing it in the right way?

1 Answer 1

1

If you want to include data as a field, you can initialize it with field(init=False) to indicate that it's value is not an argument to __init__:

from dataclasses import dataclass, field
from typing import List, Dict
import yaml

@dataclass
class Myclass:
    path: str = None
    company_name: List[str] = None
    data: Dict[str, List[str]] = field(init=False)
        
    def __post_init__(self):
        if self.path is not None:
            with open(self.path, 'r') as f:
                self.data = yaml.load(f, Loader=yaml.FullLoader)
        else:
            self.data = {'company': self.company_name}
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.