How to use the typing.TYPE_CHECKING function in typing

To help you get started, we’ve selected a few typing 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 quantumlib / Cirq / cirq / google / line / placement / chip.py View on Github external
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#         https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Dict, List, Tuple, TYPE_CHECKING

from cirq.devices import GridQubit

if TYPE_CHECKING:
    import cirq.google


EDGE = Tuple[GridQubit, GridQubit]


def above(qubit: GridQubit) -> GridQubit:
    """Gives qubit with one unit less on the second coordinate.

    Args:
        qubit: Reference qubit.

    Returns:
        New translated qubit.
    """
    return GridQubit(qubit.row, qubit.col - 1)
github PureStorage-OpenConnect / py-pure-client / pypureclient / pure1 / models / policy_get_response.py View on Github external
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)

    OpenAPI spec version: 1.0
    
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""


import pprint
import re

import six
import typing

from ...properties import Property
if typing.TYPE_CHECKING:
    from pypureclient.pure1 import models

class PolicyGetResponse(object):
    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'continuation_token': 'str',
        'total_item_count': 'int',
        'items': 'list[Policy]'
    }
github Azure / azure-sdk-for-python / sdk / storage / azure-storage-file-datalake / azure / storage / filedatalake / _deserialize.py View on Github external
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

import logging
from typing import (  # pylint: disable=unused-import
    TYPE_CHECKING
)

from azure.core.pipeline.policies import ContentDecodePolicy
from azure.core.exceptions import HttpResponseError, DecodeError, ResourceModifiedError, ClientAuthenticationError, \
    ResourceNotFoundError, ResourceExistsError
from ._shared.models import StorageErrorCode

if TYPE_CHECKING:
    pass

_LOGGER = logging.getLogger(__name__)


def normalize_headers(headers):
    normalized = {}
    for key, value in headers.items():
        if key.startswith('x-ms-'):
            key = key[5:]
        normalized[key.lower().replace('-', '_')] = value
    return normalized


def deserialize_metadata(response, obj, headers):  # pylint: disable=unused-argument
    raw_metadata = {k: v for k, v in response.headers.items() if k.startswith("x-ms-meta-")}
github oilshell / oil / frontend / args.py View on Github external
"""
from __future__ import print_function

from _devbuild.gen.runtime_asdl import (
    value, value_e, value_t, value__Bool, value__Int, value__Float, value__Str,
)

from asdl import runtime
from core.pyerror import e_usage, log
from mycpp import mylib
from mycpp.mylib import tagswitch, iteritems

from typing import (
    cast, Tuple, Optional, Dict, List, Any, IO, TYPE_CHECKING
)
if TYPE_CHECKING:
  from frontend import flag_spec
  OptChange = Tuple[str, bool]


# TODO: Move to flag_spec?  We use flag_type_t
String = 1
Int = 2
Float = 3  # e.g. for read -t timeout value
Bool = 4  # OilFlags has explicit boolean type


class _Attributes(object):
  """Object to hold flags.

  TODO: FlagSpec doesn't need this; only FlagSpecAndMore.
  """
github home-assistant / hassio-supervisor / hassio / docker / addon.py View on Github external
ENV_TIME,
    ENV_TOKEN,
    MAP_ADDONS,
    MAP_BACKUP,
    MAP_CONFIG,
    MAP_SHARE,
    MAP_SSL,
    SECURITY_DISABLE,
    SECURITY_PROFILE,
)
from ..coresys import CoreSys
from ..exceptions import DockerAPIError
from ..utils import process_lock
from .interface import DockerInterface

if TYPE_CHECKING:
    from ..addons.addon import Addon


_LOGGER: logging.Logger = logging.getLogger(__name__)

AUDIO_DEVICE = "/dev/snd:/dev/snd:rwm"
NO_ADDDRESS = ip_address("0.0.0.0")


class DockerAddon(DockerInterface):
    """Docker Hass.io wrapper for Home Assistant."""

    def __init__(self, coresys: CoreSys, addon: Addon):
        """Initialize Docker Home Assistant wrapper."""
        super().__init__(coresys)
        self.addon = addon
github eventbrite / facebook-py-sdk / facebook_sdk / authentication.py View on Github external
List,
    Mapping,
    Optional,
    Text,
    Union,
)

from facebook_sdk import (
    __version__ as VERSION,
    constants,
)
from facebook_sdk.exceptions import FacebookSDKException
from facebook_sdk.request import FacebookRequest


if TYPE_CHECKING:
    from facebook_sdk.client import FacebookClient  # noqa: F401
    from facebook_sdk.facebook import FacebookApp  # noqa: F401
    from facebook_sdk.response import FacebookResponse  # noqa: F401


class AccessToken(object):
    def __init__(self, access_token, expires_at=None):
        # type: (Text, Optional[datetime.datetime]) -> None
        super(AccessToken, self).__init__()

        self.access_token = access_token

        if expires_at:
            self.expires_at = expires_at

    def app_secret_proof(self, secret):  # type: (Text) -> Text
github zalando-incubator / kopf / kopf / reactor / queueing.py View on Github external
class WatcherCallback(Protocol):
    async def __call__(
            self,
            *,
            event: bodies.Event,
            replenished: asyncio.Event,
    ) -> None: ...


# An end-of-stream marker sent from the watcher to the workers.
# See: https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions
class EOS(enum.Enum):
    token = enum.auto()


if TYPE_CHECKING:
    WatchEventQueue = asyncio.Queue[Union[bodies.Event, EOS]]
else:
    WatchEventQueue = asyncio.Queue


class Stream(NamedTuple):
    """ A single object's stream of watch-events, with some extra helpers. """
    watchevents: WatchEventQueue
    replenished: asyncio.Event  # means: "hurry up, there are new events queued again"


ObjectUid = NewType('ObjectUid', str)
ObjectRef = Tuple[resources.Resource, ObjectUid]
Streams = MutableMapping[ObjectRef, Stream]
github twisted / klein / src / klein / interfaces.py View on Github external
EarlyExit,
    IDependencyInjector as _IDependencyInjector,
    IRequestLifecycle as _IRequestLifecycle,
    IRequiredParameter as _IRequiredParameter,
    ISession as _ISession,
    ISessionProcurer as _ISessionProcurer,
    ISessionStore as _ISessionStore,
    ISimpleAccount as _ISimpleAccount,
    ISimpleAccountBinding as _ISimpleAccountBinding,
    NoSuchSession,
    SessionMechanism,
    TooLateForCookies,
    TransactionEnded,
)

if TYPE_CHECKING:  # pragma: no cover
    from .storage._memory import MemorySessionStore, MemorySession
    from ._session import SessionProcurer, Authorization
    from ._form import Field, RenderableFormParam, FieldInjector
    from ._isession import IRequestLifecycleT as _IRequestLifecycleT
    from ._dihttp import RequestURL, RequestComponent

    from typing import Union

    ISessionStore = Union[_ISessionStore, MemorySessionStore]
    ISessionProcurer = Union[_ISessionProcurer, SessionProcurer]
    ISession = Union[_ISession, MemorySession]
    ISimpleAccount = _ISimpleAccount
    ISimpleAccountBinding = _ISimpleAccountBinding
    IDependencyInjector = Union[
        _IDependencyInjector,
        Authorization,
github pulumi / pulumi-kubernetes / sdk / python / pulumi_kubernetes / flowcontrol / __init__.py View on Github external
# coding=utf-8
# *** WARNING: this file was generated by pulumigen. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***

from .. import _utilities
import typing

# Make subpackages available:
if typing.TYPE_CHECKING:
    import pulumi_kubernetes.flowcontrol.v1alpha1 as v1alpha1
    import pulumi_kubernetes.flowcontrol.v1beta1 as v1beta1
else:
    v1alpha1 = _utilities.lazy_import('pulumi_kubernetes.flowcontrol.v1alpha1')
    v1beta1 = _utilities.lazy_import('pulumi_kubernetes.flowcontrol.v1beta1')