예제 #1
0
from msapp.bank.domain.repository import BankRepository
from typing import ForwardRef
from decimal import Decimal

Bank = ForwardRef('msapp.bank.domain.Bank')


class TransactionItem:
    bankRepository = None

    @staticmethod
    def create(data: dict, bankRepository: BankRepository):
        bank = bankRepository.probe(data['bank'])
        bank = bank if not None else data['bank']
        if 'subject' not in data or len(data['subject']) == 0:
            data['subject'] = data['name']
        return TransactionItem(data['name'], bank, data['iban'],
                               data['recipient'], data['subject'],
                               data['value'])

    def __init__(self, name: str, bank: [str, Bank], iban: str, recipient: str,
                 subject: str, value: Decimal):
        self._name = name
        self._bank = bank
        self._iban = iban
        self._recipient = recipient
        self._subject = subject
        self._value = value

    @property
    def name(self) -> str:
예제 #2
0
    def test_get_forward_reference_with_annotation_forward_reference(self):
        annotation = ForwardRef(aiplatform.Model.__name__)

        results = utils.get_forward_reference(annotation)
        self.assertEqual(results, aiplatform.Model)
예제 #3
0
и все атрибуты сущностей"""

from typing import Set, Union, List, Dict, Tuple, ForwardRef
from typing import Optional, Literal, Any
from pydantic import Json, root_validator, validator
from datetime import date, datetime, time

from app.pydantic_models.standart_methhods_redefinition import BaseModel, as_form
from app.pydantic_models.standart_methhods_redefinition import PydanticValidators
from app.pydantic_models.gen.output_ent import Developer
from app.pydantic_models.gen.output_ent import Human
from app.pydantic_models.gen.output_ent import HumanContacts
from app.pydantic_models.gen.output_ent import Admin
from app.settings.config import HOME_DIR

User = ForwardRef("User")
Smm = ForwardRef("Smm")
DirectionExpert = ForwardRef("DirectionExpert")
Competition = ForwardRef("Competition")
Direction = ForwardRef("Direction")
CompetitionDirection = ForwardRef("CompetitionDirection")
Task = ForwardRef("Task")
UserWork = ForwardRef("UserWork")
Criterion = ForwardRef("Criterion")
MarkWork = ForwardRef("MarkWork")
Page = ForwardRef("Page")
Question = ForwardRef("Question")
SimpleEntity = ForwardRef("SimpleEntity")
News = ForwardRef("News")

예제 #4
0
 def evaluate_forwardref(type_: ForwardRef, globalns: Any,
                         localns: Any) -> Type[Any]:
     return type_._eval_type(globalns, localns)
예제 #5
0
    (Optional[str], Union[str, None]),
    (Optional[Address], Union[Address, None]),
    (Optional[List[str]], Union[List[str], None]),
    (Optional[Dict[str, str]], None),
    (Optional[Dict], None),
    (Union[str], str),
    (Union[str, int], None),
    (Union[bool, None], Union[bool, None]),
    (Union[bytes, None], Union[bytes, None]),
    (Union[int, None], Union[int, None]),
    (Union[str, None], Union[str, None]),
    (Union[None, str], Union[str, None]),
    (Union[Address, None], Union[Address, None]),
    (Union[Person, None], Union[Person, None]),
    (Union["Person", None], None),
    (ForwardRef("bool"), None),
    (ForwardRef("bytes"), None),
    (ForwardRef("int"), None),
    (ForwardRef("str"), None),
    (ForwardRef("Address"), None),
    (Optional[ForwardRef("Address")], None),
    (Dict[str, ForwardRef("Address")], None),
    (Union[ForwardRef("Person"), None], None),
    (InvalidListType, None),
    (InvalidDictType, None),
    (InvalidUnionType, None),
    (InvalidNestedType, None),
    (ValidNestedType, ValidNestedType),
    (TooManyFieldsType, None),
    (MaxFieldsType, MaxFieldsType),
])
예제 #6
0
from typing import List, Optional, ForwardRef, Dict
from pydantic import BaseModel, UrlStr

ref = ForwardRef('Tweet')


class Tweet(BaseModel):
    id: str  # serializing to string because otherwise the long id gets messed up
    text: str
    stance_comment: float
    stance_support: float
    stance_query: float
    stance_deny: float
    veracity_false: Optional[float]
    veracity_true: Optional[float]
    veracity_unknown: Optional[float]
    avg_stance_comment: Optional[float]
    avg_stance_support: Optional[float]
    avg_stance_query: Optional[float]
    avg_stance_deny: Optional[float]


class Conversation(BaseModel):
    source: Tweet
    replies: Dict[str, Tweet]


class Callback(BaseModel):
    callback_url: str

예제 #7
0
class DnsServerData(BaseModel):
    id: int
    name: str
    zones: Optional[List[ForwardRef("ZoneData")]]
    created_at: datetime
예제 #8
0
class Model(ml.Model):
    """Representative model.

    [De]Serialization of API models relies on the attrs and cattrs
    libraries with some additional customization. This model represents
    these custom treatments and provides documentation for how and why
    they are needed.
    """

    # enum1 and model_no_refs1 are both defined before this class
    # yet we will still refer to them using forward reference (double quotes)
    # because we do not keep track of definition order in the generated code
    enum1: "Enum1"
    model_no_refs1: "ModelNoRefs1"

    # enum2 and model_no_refs2 are both defined after this class and so the
    # forward reference annotation is required.
    enum2: "Enum2"
    model_no_refs2: "ModelNoRefs2"

    # Optional[] and List[]
    list_enum1: Sequence["Enum1"]
    list_model_no_refs1: Sequence["ModelNoRefs1"]
    opt_enum1: Optional["Enum1"] = None
    opt_model_no_refs1: Optional["ModelNoRefs1"] = None

    # standard types
    id: Optional[int] = None
    name: Optional[str] = None

    # testing reserved keyword translations
    class_: Optional[str] = None
    finally_: Optional[Sequence[int]] = None

    # Because this model has "bare" forward ref annotated properties
    # (enum1, enum2, model_no_refs1, and model_no_refs2) we need to tell
    # the attr library that they're actually ForwardRef objects so that
    # cattr will match our forward_ref_structure_hook structure hook
    #
    #
    # Note: just doing the following:
    #
    # `converter.register_structure_hook("Enum1", structure_hook)`
    #
    # does not work. cattr stores these hooks using functools singledispatch
    # which in turn creates a weakref.WeakKeyDictionary for the dispatch_cache.
    # While the registration happens, the cache lookup throws a TypeError
    # instead of a KeyError so we never look in the registry.
    __annotations__ = {
        # python generates these entries as "enum1": "Enum1" etc, we need
        # them to be of the form "enum1": ForwardRef("Enum1")
        "enum1": ForwardRef("Enum1"),
        "model_no_refs1": ForwardRef("ModelNoRefs1"),
        "enum2": ForwardRef("Enum2"),
        "model_no_refs2": ForwardRef("ModelNoRefs2"),
        # python "correctly" inserts the remaining entries but we have to
        # define all or nothing using this API
        "list_enum1": Sequence["Enum1"],
        "list_model_no_refs1": Sequence["ModelNoRefs1"],
        "opt_enum1": Optional["Enum1"],
        "opt_model_no_refs1": Optional["ModelNoRefs1"],
        "id": Optional[int],
        "name": Optional[str],
        "class_": Optional[str],
        "finally_": Optional[Sequence[int]],
    }

    def __init__(
        self,
        *,
        enum1: "Enum1",
        model_no_refs1: "ModelNoRefs1",
        enum2: "Enum2",
        model_no_refs2: "ModelNoRefs2",
        list_enum1: Sequence["Enum1"],
        list_model_no_refs1: Sequence["ModelNoRefs1"],
        opt_enum1: Optional["Enum1"] = None,
        opt_model_no_refs1: Optional["ModelNoRefs1"] = None,
        id: Optional[int] = None,
        name: Optional[str] = None,
        class_: Optional[str] = None,
        finally_: Optional[Sequence[int]] = None,
    ):
        """Keep mypy and IDE suggestions happy.

        We cannot use the built in __init__ generation attrs offers
        because mypy complains about unknown keyword argument, even
        when kw_only=True is set below. Furthermore, IDEs do not pickup
        on the attrs generated __init__ so completion suggestion fails
        for insantiating these classes otherwise.
        """
        self.enum1 = enum1
        self.model_no_refs1 = model_no_refs1
        self.enum2 = enum2
        self.model_no_refs2 = model_no_refs2
        self.list_enum1 = list_enum1
        self.list_model_no_refs1 = list_model_no_refs1
        self.opt_enum1 = opt_enum1
        self.opt_model_no_refs1 = opt_model_no_refs1
        self.id = id
        self.name = name
        self.class_ = class_
        self.finally_ = finally_
예제 #9
0
from bergen.enums import DataPointType, HostProtocol, PostmanProtocol, ProviderProtocol
from bergen.queries.delayed.pod import POD_QUERY
from bergen.queries.delayed.template import TEMPLATE_GET_QUERY
from bergen.extenders.port import ArgPortExtender, KwargPortExtender, ReturnPortExtender
from bergen.types.object import ArnheimObject
from bergen.types.model import ArnheimModel
from enum import Enum
from typing import Any, Generic, List, Optional, Type, TypeVar
try:
    # python 3.8
    from typing import ForwardRef
except ImportError:
    # ForwardRef is private in python 3.6 and 3.7
    from typing import _ForwardRef as ForwardRef

User = ForwardRef("User")
DataModel = ForwardRef("DataModel")


class AssignationParams(ArnheimObject):
    provider: Optional[str]


class ProvisionParams(ArnheimObject):
    provider: Optional[str]
    auto_unprovide: Optional[bool]


class Avatar(ArnheimObject):
    user: Optional['User']
    avatar: Optional[str]
예제 #10
0
import yaml

# In order to use LibYAML bindings, which is much faster than pure Python.
# Download and install [LibYAML](https://pyyaml.org/wiki/LibYAML).
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper

# Exported classes & functions.
__all__ = [
    'Config',
]

AttrKey = TypeVar('AttrKey', str, bytes)
AttrValue = Union[Dict[AttrKey, ForwardRef('AttrValue')],
                  Sequence[ForwardRef('AttrValue')], int, float, str, bool]


# noinspection PyUnresolvedReferences
class Attr(dict):
    """Get attributes.

    Examples:
        ```python
        >>> d = Attr({'foo':3})
        >>> d['foo']
        3
        >>> d.foo
        3
        >>> d.bar
예제 #11
0
    objects we can just decorate the class rather than doing the
    __annotations__ hack.
    """

    name2: str

    def __init__(self, *, name2: str):
        self.name2 = name2


converter = cattr.Converter()
structure_hook = functools.partial(sr.forward_ref_structure_hook, globals(), converter)
translate_keys_structure_hook = functools.partial(
    sr.translate_keys_structure_hook, converter
)
converter.register_structure_hook(ForwardRef("Model"), structure_hook)
converter.register_structure_hook(ForwardRef("ChildModel"), structure_hook)
converter.register_structure_hook(ForwardRef("Enum1"), structure_hook)
converter.register_structure_hook(ForwardRef("Enum2"), structure_hook)
converter.register_structure_hook(ForwardRef("ModelNoRefs1"), structure_hook)
converter.register_structure_hook(ForwardRef("ModelNoRefs2"), structure_hook)
converter.register_structure_hook(Model, translate_keys_structure_hook)


MODEL_DATA = {
    "enum1": "entry1",
    "model_no_refs1": {"name1": "model_no_refs1_name"},
    "enum2": "entry2",
    "model_no_refs2": {"name2": "model_no_refs2_name"},
    "list_enum1": ["entry1"],
    "list_model_no_refs1": [{"name1": "model_no_refs1_name"}],
예제 #12
0
def test_convert_generics_pep604():
    assert (convert_generics(dict['Hero', list['Team']]
                             | int) == dict[ForwardRef('Hero'),
                                            list[ForwardRef('Team')]] | int)
예제 #13
0
# pylint: disable=missing-module-docstring,missing-class-docstring,too-few-public-methods,invalid-name

from typing import ForwardRef

Cls = ForwardRef("Cls")


class Cls:
    pass
예제 #14
0
from decimal import Decimal
from typing import Callable, Iterable, ForwardRef
import re
from msapp.datastore.gateway import Gsheet

TransactionItem = ForwardRef('msapp.bank.domain.TransactionItem')


class MonetaryDistributionData:
    def __init__(self, transactionItemFactory: Callable,
                 distributionDataSource: Gsheet, distributionConfig: dict):
        self._transactionItemFactory = transactionItemFactory
        self._dataSource = distributionDataSource
        assert 'source' in distributionConfig and 'targets' in distributionConfig, "ERROR: Distribution configuration missing."
        self._config = distributionConfig

    def source(self) -> TransactionItem:
        return self._assembleTransactionItem(self._config['source'])

    def targets(self) -> Iterable[TransactionItem]:
        targets = []
        for target in self._config['targets']:
            targets.append(self._assembleTransactionItem(target))
        return targets

    def _assembleTransactionItem(self,
                                 transactionItem: dict) -> TransactionItem:
        if type(transactionItem['value']) is dict:
            transactionItem['value'] = self._getDatastoreValue(
                transactionItem['value'],
                MonetaryDistributionData._fetchMonetaryValue)
예제 #15
0
from app.pydantic_models.gen.input_ent import CompetitionDirection
from app.pydantic_models.gen.input_ent import Page
from app.pydantic_models.gen.input_ent import User
from app.pydantic_models.gen.input_ent import SimpleEntity
from app.pydantic_models.gen.input_ent import HumanContacts
from app.pydantic_models.gen.input_ent import Smm
from app.pydantic_models.gen.input_ent import Admin
from app.pydantic_models.gen.input_ent import Direction
from app.pydantic_models.gen.input_ent import Human
from app.pydantic_models.gen.input_ent import Question
from app.pydantic_models.gen.input_ent import News
from app.pydantic_models.gen.input_ent import Competition
from app.pydantic_models.gen.input_ent import Developer
from app.settings.config import HOME_DIR

DirectionExpert = ForwardRef("DirectionExpert")
Task = ForwardRef("Task")
UserWork = ForwardRef("UserWork")
Criterion = ForwardRef("Criterion")
MarkWork = ForwardRef("MarkWork")


class DirectionExpert(BaseModel):
    username: str
    password: Optional[str] = None
    name: str
    surname: str
    email: str
    human_contacts: Union[int, HumanContacts, None] = None
    photo: Optional[str] = ''
    status: Optional[str] = ''
예제 #16
0
 class WithExplicitForwardRef:
     sibling: ForwardRef("WithExplicitForwardRef")  # noqa: F821
예제 #17
0
# standard library
from typing import Any, ForwardRef, Tuple

# third-party packages
from pytest import mark
from typing_extensions import Literal

# submodules
from xarray_dataclasses.typing import DataArrayLike, get_dims, get_dtype

# type hints
x = ForwardRef("x")
y = ForwardRef("y")
X = Literal["x"]
Y = Literal["y"]

# test datasets
testdata_dims = [
    (None, ()),
    (Tuple[()], ()),
    (X, ("x", )),
    (x, ("x", )),
    (Tuple[X], ("x", )),
    (Tuple[x], ("x", )),  # type: ignore
    (Tuple[X, Y], ("x", "y")),
    (Tuple[x, y], ("x", "y")),  # type: ignore
]

testdata_dtype = [
    (Any, None),
    (int, int),
예제 #18
0
from __future__ import annotations
from typing import cast, Optional, Sequence, Tuple, Union, ForwardRef
from typeguard import typechecked
from arkouda.client import generic_msg, get_config
from arkouda.pdarrayclass import pdarray, create_pdarray
from arkouda.pdarraycreation import zeros, zeros_like, array
from arkouda.sorting import argsort
from arkouda.strings import Strings
from arkouda.logger import getArkoudaLogger

Categorical = ForwardRef('Categorical')

__all__ = ["unique", "in1d", "concatenate", "union1d", "intersect1d",
           "setdiff1d", "setxor1d"]

logger = getArkoudaLogger(name='pdarraysetops')

@typechecked
def unique(pda : Union[pdarray,Strings,'Categorical'], # type: ignore
           return_counts : bool=False) -> Union[Union[pdarray,Strings,'Categorical'], # type: ignore
                  Tuple[Union[pdarray,Strings,'Categorical'], Optional[pdarray]]]: #type: ignore
    """
    Find the unique elements of an array.

    Returns the unique elements of an array, sorted if the values are integers. 
    There is an optional output in addition to the unique elements: the number 
    of times each unique value comes up in the input array.

    Parameters
    ----------
    pda : pdarray or Strings or Categorical
예제 #19
0

class CountryModel(BaseModel):
    id: int
    name: str
    flag_url: str

    class Config:
        orm_mode = True


class CountriesOutput(BaseModel):
    countries: List[CountryModel]


AthleteRef = ForwardRef('AthleteModel')


class TeamModel(BaseModel):
    id: int
    name: str
    group: GroupModel
    logo_url: Optional[str]
    country: CountryModel

    class Config:
        orm_mode = True
        getter_dict = PonyGetterDict


class CreateTeamInput(BaseModel):
예제 #20
0
from typing import ForwardRef, Optional, List

from pydantic import BaseModel, HttpUrl, validator

Recipe = ForwardRef('Recipe')


class LoweredStr(str):
    """
    Ensure database collation sanity by ignoring case.
    """
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v) -> str:
        try:
            s = v.lower()
        except AttributeError:
            raise TypeError(f'"{v}" is not of type str, got: {type(v)}')
        return cls(s)

    def __repr__(self):
        return f'LoweredStr({super().__repr__()})'


class Base(BaseModel):
    """
    Enable ORM Mode on all instances.
예제 #21
0
def test_restify_type_ForwardRef():
    from typing import ForwardRef  # type: ignore
    assert restify(ForwardRef("myint")) == ":class:`myint`"
예제 #22
0
 def __init__(self, f: ForwardRef("Service2")):
     pass
예제 #23
0
from typing import Dict, Optional, Tuple

from flash.core.serve.component import ModelComponent
from flash.core.serve.core import Endpoint
from flash.core.serve.types import Repeated
from flash.core.utilities.imports import _PYDANTIC_AVAILABLE

if _PYDANTIC_AVAILABLE:
    from pydantic import BaseModel, create_model
else:
    BaseModel, create_model = object, None

try:
    from typing import ForwardRef
    RequestModel = ForwardRef("RequestModel")
    ResponseModel = ForwardRef("ResponseModel")
except ImportError:
    RequestModel = None
    ResponseModel = None


class Alive(BaseModel):
    """Represent the alive-result of the endpoint ``/alive``."""

    alive: bool  # skipcq: PTC-W0052


class EndpointProtocol:
    """Records the model classes used to define an endpoints request/response body

    The request / response body schemas are generated dynamically depending
예제 #24
0
 def __init__(self, e: ForwardRef("Service4")):
     pass
예제 #25
0
import unittest
from typing import Union, ForwardRef

import untypy
from untypy.error import UntypyTypeError

Shape = Union['Square', 'Circle']
Shape2 = Union[ForwardRef('Square'), ForwardRef('Circle')]


class Square:
    pass


class Circle:
    pass


@untypy.typechecked
def useShape(s: Shape) -> None:
    pass


@untypy.typechecked
def useShape2(s: Shape2) -> None:
    pass


@untypy.typechecked
def useUnion(s: Union[Square, Circle]) -> None:
    pass
예제 #26
0
파일: utils.py 프로젝트: wade1990/hhvm
from __future__ import absolute_import, division, print_function, unicode_literals

import os
import re
import signal
from types import FrameType
from typing import BinaryIO, Callable, Iterable, Mapping, Union


try:
    from typing import ForwardRef
except ImportError:
    from typing import _ForwardRef as ForwardRef

JsonObject = Mapping[str, ForwardRef("Json")]
JsonArray = Iterable[ForwardRef("Json")]
JsonScalar = Union[str, int, float, bool, None]
Json = Union[JsonObject, JsonArray, JsonScalar]

VariableMap = Mapping[str, str]


def touch(fn: str) -> None:
    with open(fn, "a"):
        os.utime(fn, None)


def write_files(files: Mapping[str, str], dir_path: str) -> None:
    """
    Write a bunch of files into the directory at dir_path.
예제 #27
0
    def test_resolve_annotation_with_annotation_foward_typed_reference(self):
        annotation = ForwardRef(aiplatform.Model.__name__)

        results = utils.resolve_annotation(annotation)
        self.assertEqual(results, aiplatform.Model)
예제 #28
0
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT  SHALL  THE
AUTHORS  OR  COPYRIGHT  HOLDERS  BE  LIABLE  FOR  ANY CLAIM,  DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  TORT OR OTHERWISE, ARISING FROM,
OUT  OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

#=============================================================================
from typing import ForwardRef, List, Optional, Tuple, Union

from Utils.decorators import abstract
from . import ExtensionMessages, TYPE, warning


#=============================================================================
ConnectionRef = ForwardRef( "Connection" )
CursorRef     = ForwardRef( "Cursor" )


#=============================================================================
class Cursor:
    """The class of DB cursors.
    
    Copy from PEP 249:
    These objects represent a database cursor,  which  is  used  to 
    manage  the context of a fetch operation.  Cursors created from 
    the same connection are not isolated, i.e., any changes done to 
    the  database  by a cursor are immediately visible by the other 
    cursors.  Cursors created from different connections can or can 
    not  be  isolated,  depending on how the transaction support is 
    implemented  (see  also  the  connection's  '.rollback()'   and 
예제 #29
0
    mador: Mador = None
    manages_mador_name: str = None
    operates: List[Mador] = None
    permissions: List[Permission] = None
    icon_path: str = None

    class Config:
        orm_mode = True


class UserAuth(User):
    username: str
    password: str


Hierarchy = ForwardRef('Hierarchy')


class Hierarchy(BaseModel):
    """"Hierarchy for User and Commander."""
    leader: Optional[int]
    childs: List[Hierarchy]  # list of Hierarchy.


Hierarchy.update_forward_refs()


class StatusTypes(str, Enum):
    required = "required"
    not_required = "not_required"
    not_important = "not_important"
def test_bound_type_cheking_only_forward_ref_wrong_type():
    """We should check ``ForwardRef`` parameter name correctly."""
    with utils.temp_registered(ForwardRef("WrongType"), st.just(1)):
        with pytest.raises(ResolutionFailed):
            st.builds(typechecking_only_fun).example()