简体   繁体   中英

Dataclass being invoked when import (?)

I've defined this dataclass:

import logging
from config.config_parser import ConfigParser
from dataclasses import dataclass

@dataclass
class A:
    id_execution: int
    flag: bool
    log: str = logging.getLogger('log_handler')
    con: str = ConfigParser.get_conf('A', 'a_value')
    name: str = None
    surname: str = None

This dataclass is being invoked in other 'traditional' class like:

from handlers.handler_a import A
from config.config_parser import ConfigParser

# Configuration initialization
ConfigParser.initialize_config()

# Instantiate A dataclass
a = A()

ConfigParser fails because it is not initalized. It seems like A is being intialized in the above import, before the configParser and everything.

How is this possible? Am I doing something wrong?

Thanks in advance

A is not being initialized upon importing, but all those A' class variables are assigned then and so the right side of assignment like ConfigParser.get_conf('A', 'a_value') is executed.

If you make those variables instance level variables (by putting their declaration in __init__ ), they will be assigned upon calling that a = A() .

ConfigParser.get_conf('A', 'a_value') is being called during the creation of A , which is why it is failing. In a normal class, this would be written

class A:
    def __init__(self):
        self.con = ConfigParser.get_conf('A', 'a_value')

and get_conf would only be called when an instance is created.

We can tell the dataclass to do the same thing by making that attribute a field with a default_factory :

import logging from config.config_parser import ConfigParser from dataclasses import dataclass, field

@dataclass
class A:
    id_execution: int
    flag: bool
    log: str = logging.getLogger('log_handler')
    con: str = field(default_factory=lambda: ConfigParser.get_conf('A', 'a_value'))
    name: str = None
    surname: str = None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM