• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python types.MappingProxyType类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中types.MappingProxyType的典型用法代码示例。如果您正苦于以下问题:Python MappingProxyType类的具体用法?Python MappingProxyType怎么用?Python MappingProxyType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了MappingProxyType类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, entity_id: str, state: Any,
                 attributes: Optional[Dict] = None,
                 last_changed: Optional[datetime.datetime] = None,
                 last_updated: Optional[datetime.datetime] = None,
                 context: Optional[Context] = None,
                 # Temp, because database can still store invalid entity IDs
                 # Remove with 1.0 or in 2020.
                 temp_invalid_id_bypass: Optional[bool] = False) -> None:
        """Initialize a new state."""
        state = str(state)

        if not valid_entity_id(entity_id) and not temp_invalid_id_bypass:
            raise InvalidEntityFormatError((
                "Invalid entity id encountered: {}. "
                "Format should be <domain>.<object_id>").format(entity_id))

        if not valid_state(state):
            raise InvalidStateError((
                "Invalid state encountered for entity id: {}. "
                "State max length is 255 characters.").format(entity_id))

        self.entity_id = entity_id.lower()
        self.state = state  # type: str
        self.attributes = MappingProxyType(attributes or {})
        self.last_updated = last_updated or dt_util.utcnow()
        self.last_changed = last_changed or self.last_updated
        self.context = context or Context()
开发者ID:arsaboo,项目名称:home-assistant,代码行数:27,代码来源:core.py


示例2: __init__

    def __init__(self, key, mass_fractions, atomic_fractions, formula):
        """
        Private constructor. It should never be used.
        """
        if key != Composition._key:
            raise TypeError('Composition cannot be created using constructor')
        if set(mass_fractions.keys()) != set(atomic_fractions.keys()):
            raise ValueError('Mass and atomic fractions must have the same elements')

        self.mass_fractions = MappingProxyType(mass_fractions)
        self.atomic_fractions = MappingProxyType(atomic_fractions)
        self._formula = formula
开发者ID:ppinard,项目名称:pyxray,代码行数:12,代码来源:composition.py


示例3: __init__

    def __init__(self, entity_id, state, attributes=None, last_changed=None,
                 last_updated=None):
        """Initialize a new state."""
        if not valid_entity_id(entity_id):
            raise InvalidEntityFormatError((
                "Invalid entity id encountered: {}. "
                "Format should be <domain>.<object_id>").format(entity_id))

        self.entity_id = entity_id.lower()
        self.state = str(state)
        self.attributes = MappingProxyType(attributes or {})
        self.last_updated = last_updated or dt_util.utcnow()
        self.last_changed = last_changed or self.last_updated
开发者ID:zebpalmer,项目名称:home-assistant,代码行数:13,代码来源:core.py


示例4: make_crud_args

def make_crud_args(args: argparse.Namespace,
                   presets: MappingProxyType = MappingProxyType({})):

    res = presets.get(args.access_preset, {})

    relevant_cli_arguments = {k: v for k, v in vars(args).items()
                              if k in ('aws_access_key_id',
                                       'bucket_name',
                                       'endpoint_url',
                                       'aws_secret_access_key') and v is not None}

    res.update(relevant_cli_arguments)

    return res
开发者ID:hasadna,项目名称:open-bus,代码行数:14,代码来源:s3_wrapper.py


示例5: __init__

    def __init__(self, entity_id, state, attributes=None, last_changed=None,
                 last_updated=None):
        """Initialize a new state."""
        if not valid_entity_id(entity_id):
            raise InvalidEntityFormatError((
                "Invalid entity id encountered: {}. "
                "Format should be <domain>.<object_id>").format(entity_id))

        self.entity_id = entity_id.lower()
        self.state = str(state)
        self.attributes = MappingProxyType(attributes or {})
        self.last_updated = dt_util.strip_microseconds(
            last_updated or dt_util.utcnow())

        # Strip microsecond from last_changed else we cannot guarantee
        # state == State.from_dict(state.as_dict())
        # This behavior occurs because to_dict uses datetime_to_str
        # which does not preserve microseconds
        self.last_changed = dt_util.strip_microseconds(
            last_changed or self.last_updated)
开发者ID:Cinntax,项目名称:home-assistant,代码行数:20,代码来源:core.py


示例6: __init__

    def __init__(self, entity_id: str, state: Any,
                 attributes: Optional[Dict] = None,
                 last_changed: Optional[datetime.datetime] = None,
                 last_updated: Optional[datetime.datetime] = None,
                 context: Optional[Context] = None) -> None:
        """Initialize a new state."""
        state = str(state)

        if not valid_entity_id(entity_id):
            raise InvalidEntityFormatError((
                "Invalid entity id encountered: {}. "
                "Format should be <domain>.<object_id>").format(entity_id))

        if not valid_state(state):
            raise InvalidStateError((
                "Invalid state encountered for entity id: {}. "
                "State max length is 255 characters.").format(entity_id))

        self.entity_id = entity_id.lower()
        self.state = state
        self.attributes = MappingProxyType(attributes or {})
        self.last_updated = last_updated or dt_util.utcnow()
        self.last_changed = last_changed or self.last_updated
        self.context = context or Context()
开发者ID:ManHammer,项目名称:home-assistant,代码行数:24,代码来源:core.py


示例7: State

class State(object):
    """Object to represent a state within the state machine.

    entity_id: the entity that is represented.
    state: the state of the entity
    attributes: extra information on entity and state
    last_changed: last time the state was changed, not the attributes.
    last_updated: last time this object was updated.
    """

    __slots__ = ['entity_id', 'state', 'attributes',
                 'last_changed', 'last_updated']

    # pylint: disable=too-many-arguments
    def __init__(self, entity_id, state, attributes=None, last_changed=None,
                 last_updated=None):
        """Initialize a new state."""
        if not valid_entity_id(entity_id):
            raise InvalidEntityFormatError((
                "Invalid entity id encountered: {}. "
                "Format should be <domain>.<object_id>").format(entity_id))

        self.entity_id = entity_id.lower()
        self.state = str(state)
        self.attributes = MappingProxyType(attributes or {})
        self.last_updated = dt_util.strip_microseconds(
            last_updated or dt_util.utcnow())

        # Strip microsecond from last_changed else we cannot guarantee
        # state == State.from_dict(state.as_dict())
        # This behavior occurs because to_dict uses datetime_to_str
        # which does not preserve microseconds
        self.last_changed = dt_util.strip_microseconds(
            last_changed or self.last_updated)

    @property
    def domain(self):
        """Domain of this state."""
        return split_entity_id(self.entity_id)[0]

    @property
    def object_id(self):
        """Object id of this state."""
        return split_entity_id(self.entity_id)[1]

    @property
    def name(self):
        """Name of this state."""
        return (
            self.attributes.get(ATTR_FRIENDLY_NAME) or
            self.object_id.replace('_', ' '))

    def as_dict(self):
        """Return a dict representation of the State.

        To be used for JSON serialization.
        Ensures: state == State.from_dict(state.as_dict())
        """
        return {'entity_id': self.entity_id,
                'state': self.state,
                'attributes': dict(self.attributes),
                'last_changed': dt_util.datetime_to_str(self.last_changed),
                'last_updated': dt_util.datetime_to_str(self.last_updated)}

    @classmethod
    def from_dict(cls, json_dict):
        """Initialize a state from a dict.

        Ensures: state == State.from_json_dict(state.to_json_dict())
        """
        if not (json_dict and 'entity_id' in json_dict and
                'state' in json_dict):
            return None

        last_changed = json_dict.get('last_changed')

        if last_changed:
            last_changed = dt_util.str_to_datetime(last_changed)

        last_updated = json_dict.get('last_updated')

        if last_updated:
            last_updated = dt_util.str_to_datetime(last_updated)

        return cls(json_dict['entity_id'], json_dict['state'],
                   json_dict.get('attributes'), last_changed, last_updated)

    def __eq__(self, other):
        """Return the comparison of the state."""
        return (self.__class__ == other.__class__ and
                self.entity_id == other.entity_id and
                self.state == other.state and
                self.attributes == other.attributes)

    def __repr__(self):
        """Return the representation of the states."""
        attr = "; {}".format(util.repr_helper(self.attributes)) \
               if self.attributes else ""

        return "<state {}={}{} @ {}>".format(
#.........这里部分代码省略.........
开发者ID:Cinntax,项目名称:home-assistant,代码行数:101,代码来源:core.py


示例8: State

class State(object):
    """Object to represent a state within the state machine.

    entity_id: the entity that is represented.
    state: the state of the entity
    attributes: extra information on entity and state
    last_changed: last time the state was changed, not the attributes.
    last_updated: last time this object was updated.
    """

    __slots__ = ['entity_id', 'state', 'attributes',
                 'last_changed', 'last_updated']

    def __init__(self, entity_id, state, attributes=None, last_changed=None,
                 last_updated=None):
        """Initialize a new state."""
        if not valid_entity_id(entity_id):
            raise InvalidEntityFormatError((
                "Invalid entity id encountered: {}. "
                "Format should be <domain>.<object_id>").format(entity_id))

        self.entity_id = entity_id.lower()
        self.state = str(state)
        self.attributes = MappingProxyType(attributes or {})
        self.last_updated = last_updated or dt_util.utcnow()

        self.last_changed = last_changed or self.last_updated

    @property
    def domain(self):
        """Domain of this state."""
        return split_entity_id(self.entity_id)[0]

    @property
    def object_id(self):
        """Object id of this state."""
        return split_entity_id(self.entity_id)[1]

    @property
    def name(self):
        """Name of this state."""
        return (
            self.attributes.get(ATTR_FRIENDLY_NAME) or
            self.object_id.replace('_', ' '))

    def as_dict(self):
        """Return a dict representation of the State.

        Async friendly.

        To be used for JSON serialization.
        Ensures: state == State.from_dict(state.as_dict())
        """
        return {'entity_id': self.entity_id,
                'state': self.state,
                'attributes': dict(self.attributes),
                'last_changed': self.last_changed,
                'last_updated': self.last_updated}

    @classmethod
    def from_dict(cls, json_dict):
        """Initialize a state from a dict.

        Async friendly.

        Ensures: state == State.from_json_dict(state.to_json_dict())
        """
        if not (json_dict and 'entity_id' in json_dict and
                'state' in json_dict):
            return None

        last_changed = json_dict.get('last_changed')

        if isinstance(last_changed, str):
            last_changed = dt_util.parse_datetime(last_changed)

        last_updated = json_dict.get('last_updated')

        if isinstance(last_updated, str):
            last_updated = dt_util.parse_datetime(last_updated)

        return cls(json_dict['entity_id'], json_dict['state'],
                   json_dict.get('attributes'), last_changed, last_updated)

    def __eq__(self, other):
        """Return the comparison of the state."""
        return (self.__class__ == other.__class__ and
                self.entity_id == other.entity_id and
                self.state == other.state and
                self.attributes == other.attributes)

    def __repr__(self):
        """Return the representation of the states."""
        attr = "; {}".format(util.repr_helper(self.attributes)) \
               if self.attributes else ""

        return "<state {}={}{} @ {}>".format(
            self.entity_id, self.state, attr,
            dt_util.as_local(self.last_changed).isoformat())
开发者ID:arjenfvellinga,项目名称:home-assistant,代码行数:99,代码来源:core.py


示例9: MappingProxyType

cards_of_deck = MappingProxyType(OrderedDict((
    (deck['Miscellaneous Mayhem'], (
        card['Badyear Git'],
        card['Sprinkler Malfunction'],
        card['Eclipse'],
        card['Fanatic Invasion'],
        card['Friendly Fans'],
        card['Rowdy Fans'],
        card['Heckler'],
        card['Hometown Fans'],
        card['Incoming!'],
        card['Rogue Wizard'],
        card['Ball Clone'],
        card['Johnny Waterboy'],
        card['That Babe\'s Got Talent!'],
        )),
    (deck['Special Team Plays'], (
        card['Come To Papa!'],
        card['Dogged Defense'],
        card['Flea Flicker'],
        card['Fumblerooski'],
        card['Going the Extra Mile'],
        card['Heroic Leap'],
        card['New Blocking Scheme'],
        card['Perfect Kick'],
        card['Option Play'],
        card['Punt'],
        card['Spectacular Catch'],
        card['Suicide Blitz'],
        card['Wake Up Call'],
        )),
    (deck['Magic Items'], (
        card['Beguiling Bracers'],
        card['Belt of Invunerability'],
        card['Fawndough\'s Headband'],
        card['Force Shield'],
        card['Gikta\'s Strength of Da Bear'],
        card['Gloves of Holding'],
        card['Inertia Dampner'],
        card['Lucky Charm'],
        card['Magic Gloves of Jark Longarm'],
        card['Good Old Magic Codpiece'],
        card['Rabbit\'s Foot'],
        card['Ring of Teleportation'],
        card['Wand of Smashing'],
        )),
    (deck['Dirty Tricks'], (
        card['Blatant Foul'],
        card['Chop Block'],
        card['Custard Pie'],
        card['Distract'],
        card['Greased Shoes'],
        card['Gromskull\'s Exploding Runes'],
        card['Illegal Substitution'],
        card['Kicking Boots'],
        card['Pit Trap'],
        card['Spiked Ball'],
        card['Stolen Playbook'],
        card['Trampoline Trap'],
        card['Witch\'s Brew'],
        )),
    (deck['Good Karma'], (
        card['All Out Blitz'],
        card['Banana Skin'],
        card['Butterfingers'],
        card['Chainsaw'],
        card['Dazed and Confused'],
        card['Doc Bonesaw'],
        card['Extra Training'],
        card['Fan Uproar'],
        card['Hurry Up Offense'],
        card['Intensive Training'],
        card['Unsportsmanlike Conduct'],
        card['Knutt\'s Spell of Awesome Strength'],
        card['Lewd Maneuvers'],
        card['Lurve Potion'],
        card['Magic Helmet'],
        card['Miracle Worker'],
        card['One with the Kicker'],
        card['Razzle Dazzle'],
        card['Suitable Pitch'],
        card['Rune of Fear'],
        card['Scutt\'s Scroll of Weather Magic'],
        card['Stiletto'],
        card['Team Anthem'],
        card['The Fan'],
        card['The Wall'],
        card['Woof Woof!'],
        )),
    (deck['Random Events'], (
        card['Bad Habits'],
        card['Ballista'],
        card['Blackmail'],
        card['Buzzing'],
        card['Duh, Where Am I?'],
        card['Ego Trip'],
        card['Zap!'],
        card['Gimme That!'],
        card['Iron Man'],
        card['Kid Gloves'],
#.........这里部分代码省略.........
开发者ID:FUMBBLPlus,项目名称:fumbbl_base,代码行数:101,代码来源:crp.py


示例10: __setstate__

 def __setstate__(self, state):
     self.mass_fractions = MappingProxyType(state.get('mass_fractions', {}))
     self.atomic_fractions = MappingProxyType(state.get('atomic_fractions', {}))
     self._formula = state.get('formula', '')
开发者ID:ppinard,项目名称:pyxray,代码行数:4,代码来源:composition.py


示例11: object

class Composition:
    """
    Defines a composition of a compound.

    To create a composition, use the class methods:

        - :meth:`from_pure`
        - :meth:`from_formula`
        - :meth:`from_mass_fractions`
        - :meth:`from_atomic_fractions`

    Use the following attributes to access the composition values:

        - :attr:`mass_fractions`: :class:`dict` where the keys are atomic numbers and the values weight fractions.
        - :attr:`atomic_fractions`: :class:`dict` where the keys are atomic numbers and the values atomic fractions.
        - :attr:`formula`: chemical formula

    The composition object is immutable, i.e. it cannot be modified once created.
    Equality can be checked.
    It is hashable.
    It can be pickled or copied.
    """

    _key = object()
    PRECISION = 0.000000001 # 1ppb

    def __init__(self, key, mass_fractions, atomic_fractions, formula):
        """
        Private constructor. It should never be used.
        """
        if key != Composition._key:
            raise TypeError('Composition cannot be created using constructor')
        if set(mass_fractions.keys()) != set(atomic_fractions.keys()):
            raise ValueError('Mass and atomic fractions must have the same elements')

        self.mass_fractions = MappingProxyType(mass_fractions)
        self.atomic_fractions = MappingProxyType(atomic_fractions)
        self._formula = formula

    @classmethod
    def from_pure(cls, z):
        """
        Creates a pure composition.

        Args:
            z (int): atomic number
        """
        return cls(cls._key, {z: 1.0}, {z: 1.0}, pyxray.element_symbol(z))

    @classmethod
    def from_formula(cls, formula):
        """
        Creates a composition from a chemical formula.

        Args:
            formula (str): chemical formula
        """
        atomic_fractions = convert_formula_to_atomic_fractions(formula)
        return cls.from_atomic_fractions(atomic_fractions)

    @classmethod
    def from_mass_fractions(cls, mass_fractions, formula=None):
        """
        Creates a composition from a mass fraction :class:`dict`.

        Args:
            mass_fractions (dict): mass fraction :class:`dict`.
                The keys are atomic numbers and the values weight fractions.
                Wildcard are accepted, e.g. ``{5: '?', 25: 0.4}`` where boron
                will get a mass fraction of 0.6.
            formula (str): optional chemical formula for the composition.
                If ``None``, a formula will be generated for the composition.
        """
        mass_fractions = process_wildcard(mass_fractions)
        atomic_fractions = convert_mass_to_atomic_fractions(mass_fractions)
        if not formula:
            formula = generate_name(atomic_fractions)
        return cls(cls._key, mass_fractions, atomic_fractions, formula)

    @classmethod
    def from_atomic_fractions(cls, atomic_fractions, formula=None):
        """
        Creates a composition from an atomic fraction :class:`dict`.

        Args:
            atomic_fractions (dict): atomic fraction :class:`dict`.
                The keys are atomic numbers and the values atomic fractions.
                Wildcard are accepted, e.g. ``{5: '?', 25: 0.4}`` where boron
                will get a atomic fraction of 0.6.
            formula (str): optional chemical formula for the composition.
                If ``None``, a formula will be generated for the composition.
        """
        atomic_fractions = process_wildcard(atomic_fractions)
        mass_fractions = convert_atomic_to_mass_fractions(atomic_fractions)
        if not formula:
            formula = generate_name(atomic_fractions)
        return cls(cls._key, mass_fractions, atomic_fractions, formula)

    def __len__(self):
        return len(self.mass_fractions)
#.........这里部分代码省略.........
开发者ID:ppinard,项目名称:pyxray,代码行数:101,代码来源:composition.py


示例12: MappingProxyType

skill_by_skillcat = MappingProxyType(OrderedDict((
    (skillcat['GENERAL'], frozenset((
        skill['Block'],
        skill['Dauntless'],
        skill['Dirty Player'],
        skill['Frenzy'],
        skill['Kick'],
        skill['Leader'],
        skill['Nerves of Steel'],
        skill['Pass Block'],
        skill['Pro'],
        skill['Shadowing'],
        skill['Strip Ball'],
        skill['Sure Hands'],
        skill['Tackle'],
        ))),
    (skillcat['AGILITY'], frozenset((
        skill['Catch'],
        skill['Diving Catch'],
        skill['Diving Tackle'],
        skill['Dodge'],
        skill['Jump Up'],
        skill['Leap'],
        skill['Side Step'],
        skill['Sprint'],
        skill['Sure Feet'],
        ))),
    (skillcat['STRENGTH'], frozenset((
        skill['Break Tackle'],
        skill['Guard'],
        skill['Mighty Blow'],
        skill['Multiple Block'],
        skill['Piling On'],
        skill['Stand Firm'],
        ))),
    (skillcat['PASSING'], frozenset((
        skill['Accurate'],
        skill['Dump-Off'],
        skill['Hail Mary'],
        skill['Pass'],
        skill['Safe Throw'],
        skill['Strong Arm'],
        ))),
    (skillcat['PHYSICAL'], frozenset((
        skill['Big Hand'],
        skill['Claw(s)'],
        skill['Extra Arms'],
        skill['Foul Appearance'],
        skill['Horns'],
        skill['Prehensile Tail'],
        skill['Razor Sharp Claws'],
        skill['Spikes'],
        skill['Tentacles'],
        skill['Thick Skull'],
        skill['Two Heads'],
        skill['Very Long Legs'],
        ))),
    (skillcat['RACIAL CHARACTERISTICS'], frozenset((
        skill['Always Hungry'],
        skill['Big Guy'],
        skill['Blood Lust'],
        skill['Bone Head'],
        skill['Easily Confused'],
        skill['Hypnotic Gaze'],
        skill['Nurgle\'s Rot'],
        skill['Really Stupid'],
        skill['Regeneration'],
        skill['Right Stuff'],
        skill['Stunty'],
        skill['Take Root'],
        skill['Throw Team-Mate'],
        skill['Thrud\'s Fans'],
        skill['Wild Animal'],
        ))),
    )))
开发者ID:FUMBBLPlus,项目名称:fumbbl_base,代码行数:75,代码来源:lrb4.py



注:本文中的types.MappingProxyType类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python types.ModuleType类代码示例发布时间:2022-05-27
下一篇:
Python types.FunctionType类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap