How to use the dataclasses.field function in dataclasses

To help you get started, we’ve selected a few dataclasses examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github omry / omegaconf / tests / structured_conf / data / dataclasses.py View on Github external
@dataclass
class ErrorDictIntKey:
    # invalid dict key, must be str
    dict: Dict[int, str] = field(default_factory=lambda: {10: "foo", 20: "bar"})


class RegularClass:
    pass


@dataclass
class ErrorDictUnsupportedValue:
    # invalid dict value type, not one of the supported types
    dict: Dict[str, RegularClass] = field(default_factory=dict)


@dataclass
class ErrorListUnsupportedValue:
    # invalid dict value type, not one of the supported types
    dict: List[RegularClass] = field(default_factory=list)


@dataclass
class ErrorListUnsupportedStructuredConfig:
    # Nesting of structured configs in Dict and List is not currently supported
    list: List[User] = field(default_factory=list)


@dataclass
class ListExamples:
github scrapinghub / arche / src / arche / rules / result.py View on Github external
@dataclass
class Result:
    """
    Args:
        name: a rule name
        messages: messages separated by severity
        stats: pandas data to plot
        items_count: the count of verified items
        err_keys: keys of all error items
        err_items_count: the number of error items
        _figures: a list of graphs created from stats
    """

    name: str
    messages: Dict[Level, List[Message]] = field(default_factory=dict)
    _stats: List[Stat] = field(default_factory=list)
    more_stats: Dict[str, Dict] = field(default_factory=dict)
    items_count: int = 0
    _err_keys: Set[Union[str, int]] = field(default_factory=set)
    _err_items_count: int = 0
    _figures: List[go.FigureWidget] = field(default_factory=list)
    _outcome: Optional[Outcome] = None

    @property
    def info(self):
        return self.messages.get(Level.INFO)

    @property
    def warnings(self):
        return self.messages.get(Level.WARNING)

    @property
github ltworf / localslackirc / slack.py View on Github external
subtype: Literal['bot_message']
    text: str
    bot_id: Optional[str]
    username: str = 'bot'
    ts: float = 0
    files: List[File] = field(default_factory=list)
    thread_ts: Optional[str] = None


@dataclass
class HistoryMessage:
    type: Literal['message']
    user: str
    text: str
    ts: float
    files: List[File] = field(default_factory=list)
    thread_ts: Optional[str] = None


class NextCursor(NamedTuple):
    next_cursor: str


class History(NamedTuple):
    ok: Literal[True]
    messages: List[Union[HistoryMessage, HistoryBotMessage]]
    has_more: bool
    response_metadata: Optional[NextCursor] = None


SlackEvent = Union[
    TopicChange,
github lebrice / SimpleParsing / examples / merging / multiple_lists_example.py View on Github external
(i.e., if the attribute is a `str`, the argument becomes a list of `str`, one for each class instance). 

For more info, check out the docstring of the `ConflictResolution` enum.
"""

from dataclasses import dataclass, field
from typing import List, Tuple

from simple_parsing import ArgumentParser, ConflictResolution

@dataclass
class CNNStack():
    name: str = "stack"
    num_layers: int = 3
    kernel_sizes: Tuple[int,int,int] = (7, 5, 5)
    num_filters: List[int] = field(default_factory=[32, 64, 64].copy)

parser = ArgumentParser(conflict_resolution=ConflictResolution.ALWAYS_MERGE)

num_stacks = 3
for i in range(num_stacks):
    parser.add_arguments(CNNStack, dest=f"stack_{i}", default=CNNStack())

args = parser.parse_args()
stack_0 = args.stack_0
stack_1 = args.stack_1
stack_2 = args.stack_2

# BUG: When the list length and the number of instances to parse is the same,
# AND there is no default value passed to `add_arguments`, it gets parsed as
# multiple lists each with only one element, rather than duplicating the field's
# default value correctly.
github fishtown-analytics / dbt / core / dbt / contracts / project.py View on Github external
data_paths: Optional[List[str]] = None
    test_paths: Optional[List[str]] = None
    analysis_paths: Optional[List[str]] = None
    docs_paths: Optional[List[str]] = None
    target_path: Optional[str] = None
    snapshot_paths: Optional[List[str]] = None
    clean_targets: Optional[List[str]] = None
    profile: Optional[str] = None
    log_path: Optional[str] = None
    modules_path: Optional[str] = None
    quoting: Optional[Quoting] = None
    on_run_start: Optional[List[str]] = field(default_factory=list_str)
    on_run_end: Optional[List[str]] = field(default_factory=list_str)
    require_dbt_version: Optional[Union[List[str], str]] = None
    models: Dict[str, Any] = field(default_factory=dict)
    seeds: Dict[str, Any] = field(default_factory=dict)
    snapshots: Dict[str, Any] = field(default_factory=dict)
    packages: List[PackageSpec] = field(default_factory=list)
    query_comment: Optional[Union[str, NoValue]] = NoValue()

    @classmethod
    def from_dict(cls, data, validate=True):
        result = super().from_dict(data, validate=validate)
        if result.name in BANNED_PROJECT_NAMES:
            raise ValidationError(
                'Invalid project name: {} is a reserved word'
                .format(result.name)
            )
        return result


@dataclass
github AlesTsurko / cells / cells / model.py View on Github external
class RegexSubstitution:
    regex: str = field(default="")
    substitution: str = field(default="")


@dataclass_json
@dataclass
class BackendMiddlewareModel:
    input: RegexSubstitution = field(default=RegexSubstitution())
    output: RegexSubstitution = field(default=RegexSubstitution())


@dataclass_json
@dataclass
class TrackTemplateModel:
    backend_name: str = field(default="Default")
    setup_code: str = field(default="")
    run_command: str = field(default="")
    command_prompt: str = field(default="")
    description: str = field(default="")
    editor_mode: str = field(default="plain text")
    path: str = field(default="")
    icon_name: str = field(default="")
    backend_middleware: BackendMiddlewareModel = field(
        default=BackendMiddlewareModel())

    def __repr__(self):
        return f"Path: {self.path}\n" +\
               f"Backend Name: {self.backend_name}\n" +\
               f"Run Command: {self.run_command}\n" +\
               f"Command Prompt: {self.command_prompt}\n" +\
               f"Editor Mode: {self.editor_mode}\n" +\
github sns-sdks / python-youtube / pyyoutube / models / video.py View on Github external
likeCount: Optional[int] = field(default=None)
    dislikeCount: Optional[int] = field(default=None, repr=False)
    commentCount: Optional[int] = field(default=None, repr=False)


@dataclass
class VideoStatus(BaseModel, DatetimeTimeMixin):
    """
    A class representing the video status info.

    Refer: https://developers.google.com/youtube/v3/docs/videos#status
    """

    uploadStatus: Optional[str] = field(default=None)
    failureReason: Optional[str] = field(default=None, repr=False)
    rejectionReason: Optional[str] = field(default=None, repr=False)
    privacyStatus: Optional[str] = field(default=None)
    publishAt: Optional[str] = field(default=None, repr=False)
    license: Optional[str] = field(default=None, repr=False)
    embeddable: Optional[bool] = field(default=None, repr=False)
    publicStatsViewable: Optional[bool] = field(default=None, repr=False)


@dataclass
class Video(BaseResource):
    """
    A class representing the video info.

    Refer: https://developers.google.com/youtube/v3/docs/videos
    """

    snippet: Optional[VideoSnippet] = field(default=None, repr=False)
github rotki / rotki / rotkehlchen / assets / asset.py View on Github external
'BSV': 'BCHSV',
    # ETHOS is known as BQX in Binance
    'ETHOS': 'BQX',
    # GXChain is GXS in Binance but GXC in Rotkehlchen
    'GXC': 'GXS',
    # YOYOW is known as YOYO in Binance
    'YOYOW': 'YOYO',
}


@total_ordering
@dataclass(init=True, repr=True, eq=False, order=False, unsafe_hash=False, frozen=True)
class Asset():
    identifier: str
    name: str = field(init=False)
    symbol: str = field(init=False)
    active: bool = field(init=False)
    asset_type: AssetType = field(init=False)
    started: Timestamp = field(init=False)
    ended: Optional[Timestamp] = field(init=False)
    forked: Optional[str] = field(init=False)
    swapped_for: Optional[str] = field(init=False)

    def __post_init__(self) -> None:
        """
        Asset post initialization

        The only thing that is given to initialize an asset is a string.

        If a non string is given then it's probably a deserialization error or
        invalid data were given to us by the server if an API was queried.
        """
github keybase / pykeybasebot / pykeybasebot / types / chat1 / __init__.py View on Github external
@dataclass_json
@dataclass
class MessageSummary:
    msg_id: MessageID = field(metadata=config(field_name="msgID"))
    message_type: MessageType = field(metadata=config(field_name="messageType"))
    tlf_name: str = field(metadata=config(field_name="tlfName"))
    tlf_public: bool = field(metadata=config(field_name="tlfPublic"))
    ctime: gregor1.Time = field(metadata=config(field_name="ctime"))


@dataclass_json
@dataclass
class Reaction:
    ctime: gregor1.Time = field(metadata=config(field_name="ctime"))
    reaction_msg_id: MessageID = field(metadata=config(field_name="reactionMsgID"))


@dataclass_json
@dataclass
class MessageServerHeader:
    message_id: MessageID = field(metadata=config(field_name="messageID"))
    superseded_by: MessageID = field(metadata=config(field_name="supersededBy"))
    ctime: gregor1.Time = field(metadata=config(field_name="ctime"))
    now: gregor1.Time = field(metadata=config(field_name="n"))
    reaction_i_ds: Optional[Optional[List[MessageID]]] = field(
        default=None, metadata=config(field_name="r")
    )
    unfurl_i_ds: Optional[Optional[List[MessageID]]] = field(
        default=None, metadata=config(field_name="u")
    )
    replies: Optional[Optional[List[MessageID]]] = field(