Reputation: 868
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?
Upvotes: 0
Views: 375
Reputation: 61042
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}
Upvotes: 1