python类Container()的实例源码

type_util.py 文件源码 项目:pytypes 作者: Stewori 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def get_Generic_parameters(tp, generic_supertype):
    """tp must be a subclass of generic_supertype.
    Retrieves the type values from tp that correspond to parameters
    defined by generic_supertype.

    E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent
    to get_Mapping_key_value(tp) except for the error message.

    Note that get_Generic_itemtype(tp) is not exactly equal to
    get_Generic_parameters(tp, typing.Container), as that method
    additionally contains treatment for typing.Tuple and typing.Iterable.
    """
    try:
        res = _select_Generic_superclass_parameters(tp, generic_supertype)
    except TypeError:
        res = None
    if res is None:
        raise TypeError("%s has no proper parameters defined by %s."%
                (type_str(tp), type_str(generic_supertype)))
    else:
        return tuple(res)
orm.py 文件源码 项目:maas 作者: maas 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def parse_item_specifier_type(
        specifier, spec_types: Container=None, separator=':'):
    """
    Returns a tuple that splits the string int a specifier, and its specifier
    type.

    Retruns a tuple of (specifier, specifier_type). If no specifier type could
    be found in the set, returns None in place of the specifier_type.

    :param specifier: The specifier string, such as "ip:10.0.0.1".
    :param spec_types: A container whose elements are strings that will be
        recognized as specifier types.
    :param separator: Optional specifier. Defaults to ':'.
    :return: tuple
    """
    if separator in specifier:
        tokens = specifier.split(separator, 1)
        if tokens[0] in spec_types:
            specifier_type = tokens[0]
            specifier = tokens[1].strip()
        else:
            specifier_type = None
    else:
        specifier_type = None
    return specifier, specifier_type
test_typechecker.py 文件源码 项目:pytypes 作者: Stewori 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_empty(self):
        asg = {Dict, List, Set, pytypes.Empty}

        empty_dict = pytypes.Empty[Dict]
        self.assertEqual(pytypes.deep_type({}), empty_dict)
        self.assertEqual(pytypes.type_str(empty_dict, asg), 'Empty[Dict]')
        self.assertTrue(pytypes.is_subtype(empty_dict, pytypes.Empty))
        #self.assertFalse(pytypes.is_subtype(Dict[str, int], empty_dict))
        self.assertTrue(pytypes.is_subtype(empty_dict, Dict[str, int]))
        self.assertTrue(pytypes.is_subtype(empty_dict, Dict))

        empty_lst = pytypes.Empty[List]
        self.assertEqual(pytypes.deep_type([]), empty_lst)
        self.assertEqual(pytypes.type_str(empty_lst, asg), 'Empty[List]')
        self.assertTrue(pytypes.is_subtype(empty_lst, pytypes.Empty))
        #self.assertFalse(pytypes.is_subtype(List[str], empty_lst))
        self.assertTrue(pytypes.is_subtype(empty_lst, List[int]))
        self.assertTrue(pytypes.is_subtype(empty_lst, List))
        self.assertFalse(pytypes.is_subtype(empty_lst, empty_dict))
        self.assertFalse(pytypes.is_subtype(empty_dict, empty_lst))

        empty_seq = pytypes.Empty[Sequence]
        empty_con = pytypes.Empty[typing.Container]
        self.assertTrue(pytypes.is_subtype(Dict[str, int],
                typing.Container[str]))
        self.assertFalse(pytypes.is_subtype(empty_dict, empty_seq))
        self.assertTrue(pytypes.is_subtype(empty_dict, empty_con))
        self.assertTrue(pytypes.is_subtype(empty_lst, empty_seq))
        self.assertFalse(pytypes.is_subtype(empty_seq, empty_lst))

        empty_set = pytypes.Empty[Set]
        self.assertEqual(pytypes.deep_type(set()), empty_set)
        self.assertEqual(pytypes.type_str(empty_set, asg), 'Empty[Set]')
        self.assertTrue(pytypes.is_subtype(empty_set, pytypes.Empty))
        #self.assertFalse(pytypes.is_subtype(Set[int], empty_set))
        self.assertTrue(pytypes.is_subtype(empty_set, Set[int]))
        self.assertTrue(pytypes.is_subtype(empty_set, Set))
type_util.py 文件源码 项目:pytypes 作者: Stewori 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def get_Generic_itemtype(sq, simplify=True):
    """Retrieves the item type from a PEP 484 generic or subclass of such.
    sq must be a typing.Tuple or (subclass of) typing.Iterable or typing.Container.
    Consequently this also works with typing.List, typing.Set and typing.Dict.
    Note that for typing.Dict and mapping types in general, the key type is regarded as item type.
    For typing.Tuple all contained types are returned as a typing.Union.
    If simplify == True some effort is taken to eliminate redundancies in such a union.
    """
    if isinstance(sq, TupleMeta):
        if simplify:
            itm_tps = [x for x in get_Tuple_params(sq)]
            simplify_for_Union(itm_tps)
            return Union[tuple(itm_tps)]
        else:
            return Union[get_Tuple_params(sq)]
    else:
        try:
            res = _select_Generic_superclass_parameters(sq, typing.Container)
        except TypeError:
            res = None
        if res is None:
            try:
                res = _select_Generic_superclass_parameters(sq, typing.Iterable)
            except TypeError:
                pass
        if res is None:
            raise TypeError("Has no itemtype: "+type_str(sq))
        else:
            return res[0]
middleware.py 文件源码 项目:falcon-marshmallow 作者: ihiji 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, required_methods=JSON_CONTENT_REQUIRED_METHODS):
        # type: (Container) -> None
        """Initialize the middleware

        :param required_methods: a collection of HTTP methods for
            which "application/json" should be required as a
            Content-Type header
        """
        log.debug('JSONEnforcer.__init__(%s)', required_methods)
        self._methods = required_methods
many_to_one.py 文件源码 项目:matchpy 作者: HPAC 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _get_name_for_position(position: List[int], variables: Container[str]) -> str:
        new_name = 'i{}'.format('.'.join(map(str, position)))
        if new_name in variables:
            counter = 1
            while '{}_{}'.format(new_name, counter) in variables:
                counter += 1
            new_name = '{}_{}'.format(new_name, counter)
        return new_name
assert_mixin.py 文件源码 项目:data-store 作者: HumanCellAtlas 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def assertResponse(
            self,
            method: str,
            path: str,
            expected_code: typing.Union[int, typing.Container[int]],
            json_request_body: typing.Optional[dict]=None,
            expected_error: typing.Optional[ExpectedErrorFields]=None,
            **kwargs) -> DSSAssertResponse:
        """
        Make a request given a HTTP method and a path.  The HTTP status code is checked against `expected_code`.

        If json_request_body is provided, it is serialized and set as the request body, and the content-type of the
        request is set to application/json.

        The first element of the return value is the response object.  The second element of the return value is the
        response text.  Attempt to parse the response body as JSON and return that as the third element of the return
        value.  Otherwise, the third element of the return value is None.

        If expected_error is provided, the content-type is expected to be "application/problem+json" and the response is
        tested in accordance to the documentation of `ExpectedErrorFields`.
        """
        if json_request_body is not None:
            if 'data' in kwargs:
                self.fail("both json_input and data are defined")
            kwargs['data'] = json.dumps(json_request_body)
            if 'headers' not in kwargs:
                kwargs['headers'] = {}
            kwargs['headers']['Content-Type'] = "application/json"

        response = getattr(self.app, method)(path, **kwargs)
        try:
            actual_json = response.json()
        except json.decoder.JSONDecodeError:
            actual_json = None

        try:
            if isinstance(expected_code, collections.abc.Container):
                self.assertIn(response.status_code, expected_code)
            else:
                self.assertEqual(response.status_code, expected_code)

            if expected_error is not None:
                self.assertEqual(response.headers['content-type'], "application/problem+json")
                self.assertEqual(actual_json['code'], expected_error.code)
                self.assertIn('title', actual_json)
                if expected_error.status is not None:
                    self.assertEqual(actual_json['status'], expected_error.status)
                if expected_error.expect_stacktrace is not None:
                    self.assertEqual('stacktrace' in actual_json, expected_error.expect_stacktrace)
        except AssertionError:
            if actual_json is not None:
                print("Response:")
                pprint.pprint(actual_json)
            raise

        return DSSAssertResponse(response, response.content, actual_json)


问题


面经


文章

微信
公众号

扫码关注公众号