当前位置: 首页>>代码示例>>Python>>正文


Python typing.TypeVar方法代码示例

本文整理汇总了Python中typing.TypeVar方法的典型用法代码示例。如果您正苦于以下问题:Python typing.TypeVar方法的具体用法?Python typing.TypeVar怎么用?Python typing.TypeVar使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在typing的用法示例。


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

示例1: test_generic_extending

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def test_generic_extending(self):
        S = TypeVar('S')
        T = TypeVar('T')

        @dataclass
        class Base(Generic[T, S]):
            x: T
            y: S

        @dataclass
        class DataDerived(Base[int, T]):
            new_field: str
        Alias = DataDerived[str]
        c = Alias(0, 'test1', 'test2')
        self.assertEqual(astuple(c), (0, 'test1', 'test2'))

        class NonDataDerived(Base[int, T]):
            def new_method(self):
                return self.y
        Alias = NonDataDerived[float]
        c = Alias(10, 1.0)
        self.assertEqual(c.new_method(), 1.0) 
开发者ID:ericvsmith,项目名称:dataclasses,代码行数:24,代码来源:test_dataclasses.py

示例2: test_generic_dynamic

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def test_generic_dynamic(self):
        T = TypeVar('T')

        @dataclass
        class Parent(Generic[T]):
            x: T
        Child = make_dataclass('Child', [('y', T), ('z', Optional[T], None)],
                               bases=(Parent[int], Generic[T]), namespace={'other': 42})
        self.assertIs(Child[int](1, 2).z, None)
        self.assertEqual(Child[int](1, 2, 3).z, 3)
        self.assertEqual(Child[int](1, 2, 3).other, 42)
        # Check that type aliases work correctly.
        Alias = Child[T]
        self.assertEqual(Alias[int](1, 2).x, 1)
        # Check MRO resolution.
        self.assertEqual(Child.__mro__, (Child, Parent, Generic, object)) 
开发者ID:ericvsmith,项目名称:dataclasses,代码行数:18,代码来源:test_dataclasses.py

示例3: test_pickle

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def test_pickle(self):
        T = TypeVar('T')
        class B(Generic[T]):
            pass
        global C  # pickle wants to reference the class by name
        class C(B[int]):
            pass
        c = C()
        c.foo = 42
        c.bar = 'abc'
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            z = pickle.dumps(c, proto)
            x = pickle.loads(z)
            self.assertEqual(x.foo, 42)
            self.assertEqual(x.bar, 'abc')
            self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'}) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:18,代码来源:test_typing.py

示例4: test_type_erasure

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def test_type_erasure(self):
        T = TypeVar('T')

        class Node(Generic[T]):
            def __init__(self, label: T,
                         left: 'Node[T]' = None,
                         right: 'Node[T]' = None):
                self.label = label  # type: T
                self.left = left  # type: Optional[Node[T]]
                self.right = right  # type: Optional[Node[T]]

        def foo(x: T):
            a = Node(x)
            b = Node[T](x)
            c = Node[Any](x)
            assert type(a) is Node
            assert type(b) is Node
            assert type(c) is Node

        foo(42) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:22,代码来源:test_typing.py

示例5: build_vocab

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def build_vocab(self, dataset: List[List[int]]) -> TypeVar("IndexField"):

        # Get current max token in vocab_dict
        max_tkn = self.current_max_token

        if isinstance(dataset, list):
            # Loop through build_vocab
            for element in dataset:
                if isinstance(element, list) or isinstance(element, int):
                    self.build_vocab(element)
                else:
                    raise TypeError(f"{type(element).__name__} not allowed.")
        
        elif isinstance(dataset, int):
            max_tkn += 1
            if dataset not in self.vocab_dict:
                self.vocab_dict[dataset] = max_tkn
        
        else:
            raise TypeError(f"{type(dataset).__name__} not allowed.")
        
        # Update inverse_vocab_dict
        self._build_inverse_dict()
        
        return self 
开发者ID:p768lwy3,项目名称:torecsys,代码行数:27,代码来源:index_field.py

示例6: bind_inputs

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def bind_inputs(self, inputs: _Inputs) -> TypeVar("Trainer"):
        r"""Bind inputs to the trainer.inputs
        
        Args:
            inputs (torecsys.inputs.base._Inputs): Inputs to be binded to the trainer.inputs.
        
        Raises:
            TypeError: whether type of inputs is not allowed to be setted.
        
        Returns:
            torecsys.trainer.Trainer: self
        """
        # Check if the type of inputs is allowed
        if not isinstance(inputs, _Inputs):
            raise TypeError("inputs must be a torecsys.inputs.base._Inputs object.")
        
        # Bind inputs to _inputs
        self._inputs = inputs

        # Apply cuda to inputs if is_cuda is True
        if self.is_cuda():
            self._inputs.cuda()

        return self 
开发者ID:p768lwy3,项目名称:torecsys,代码行数:26,代码来源:trainer.py

示例7: set_negative_size

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def set_negative_size(self, negative_size: int) -> TypeVar("Trainer"):
        r"""Set number of negative samples to be generated per batch to the trainer
        
        Args:
            negative_size (int): number of negative samples to be generated per batch.
        
        Raises:
            TypeError: when type of negative_size is not allowed.
        
        Returns:
            torecsys.trainer.Trainer: self
        """
        if not isinstance(negative_size, int):
            raise TypeError("negative_size must be int.")
        
        self._negative_size = negative_size

        return self 
开发者ID:p768lwy3,项目名称:torecsys,代码行数:20,代码来源:trainer.py

示例8: set_targets_name

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def set_targets_name(self, targets_name: str) -> TypeVar("Trainer"):
        r"""Set targets_name of the trainer.
        
        Args:
            targets_name (str): targets name to be setted for getting targets field in batch.
        
        Raises:
            TypeError: when type of targets_name is not allowed.
        
        Returns:
            torecsys.trainer.Trainer: self
        """
        if not isinstance(targets_name, str):
            raise TypeError(f"{type(targets_name).__name__} not allowed.")

        self._targets_name = targets_name
        return self 
开发者ID:p768lwy3,项目名称:torecsys,代码行数:19,代码来源:trainer.py

示例9: set_dtype

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def set_dtype(self, dtype: str) -> TypeVar("Trainer"):
        r"""Set data type of trainer.
        
        Args:
            dtype (str): data type of trainer to be setted.
        
        Raises:
            AssertionError: when dtype is not allowed.
        
        Returns:
            torecsys.trainer.Trainer: self
        """
        # Check if dtype is allowed
        if dtype not in ["double", "float", "half"]:
            raise AssertionError(f"{dtype} not found.")
        
        # Bind dtype to _dtype
        self._dtype = dtype

        # Call methods of _inputs and _model to applied data type changes
        self._inputs = getattr(self._inputs, dtype)()
        self._model = getattr(self._model, dtype)()

        return self 
开发者ID:p768lwy3,项目名称:torecsys,代码行数:26,代码来源:trainer.py

示例10: set_max_num_iterations

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def set_max_num_iterations(self, max_num_iterations: int) -> TypeVar("Trainer"):
        r"""Set maximum number of training iterations to the trainer
        
        Args:
            max_num_iterations (int): maximum number of training iterations.
        
        Raises:
            TypeError: when type of max_num_iterations is not allowed.
        
        Returns:
            torecsys.trainer.Trainer: self
        """
        if not isinstance(max_num_iterations, int):
            raise TypeError("max_num_iterations must be int.")
        
        self._max_num_iterations = max_num_iterations

        return self 
开发者ID:p768lwy3,项目名称:torecsys,代码行数:20,代码来源:trainer.py

示例11: to

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def to(self, device: Union[str, torch.device]) -> TypeVar("Trainer"):
        r"""Set device of trainer.
        
        Args:
            device (str): device to be used for training.
        
        Raises:
            TypeError: when device is not allowed
        
        Returns:
            torecsys.trainer.Trainer: self
        """
        if device == "cuda":
            return self.cuda()
        elif device == "cpu":
            return self.cpu()
        elif isinstance(device, torch.device):
            self.to(device.type)
        else:
            raise TypeError(f"{type(device).__name__} not allowed.") 
开发者ID:p768lwy3,项目名称:torecsys,代码行数:22,代码来源:trainer.py

示例12: cpu

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def cpu(self) -> TypeVar("Trainer"):
        r"""Disable GPU computation of trainer.
        
        Returns:
            torecsys.trainer.Trainer: self
        """
        if self.has_inputs:
            self._inputs.cpu()

        if self.has_model:
            self._model.cpu()
        
        if self.has_criterion:
            self.criterion.cpu()
        
        self._use_cuda = False
        self._devices = None
        
        return self 
开发者ID:p768lwy3,项目名称:torecsys,代码行数:21,代码来源:trainer.py

示例13: train

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def train(self) -> TypeVar("Trainer"):
        r"""Set trainer to train mode.
        
        Returns:
            torecsys.trainer.Trainer: self
        """
        self._current_mode = "train"
        self._sequential.train()

        if self.has_criterion and isinstance(self.criterion, nn.Module):
            self.criterion.train()
        
        # if self.has_metrics and isinstance(self.metric, nn.Module):
        #     self.metric.train()
        
        return self 
开发者ID:p768lwy3,项目名称:torecsys,代码行数:18,代码来源:trainer.py

示例14: __link_samplers

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def __link_samplers(animation: gltf2_io.Animation, export_settings):
    """
    Move animation samplers to their own list and store their indices at their previous locations.

    After gathering, samplers are stored in the channels properties of the animation and need to be moved
    to their own list while storing an index into this list at the position where they previously were.
    This behaviour is similar to that of the glTFExporter that traverses all nodes
    :param animation:
    :param export_settings:
    :return:
    """
    # TODO: move this to some util module and update gltf2 exporter also
    T = typing.TypeVar('T')

    def __append_unique_and_get_index(l: typing.List[T], item: T):
        if item in l:
            return l.index(item)
        else:
            index = len(l)
            l.append(item)
            return index

    for i, channel in enumerate(animation.channels):
        animation.channels[i].sampler = __append_unique_and_get_index(animation.samplers, channel.sampler) 
开发者ID:KhronosGroup,项目名称:glTF-Blender-IO,代码行数:26,代码来源:gltf2_blender_gather_animations.py

示例15: is_closed_python_set_type

# 需要导入模块: import typing [as 别名]
# 或者: from typing import TypeVar [as 别名]
def is_closed_python_set_type(ttype):
    '''
    A "closed" generic type has all of its type parameters parameterized
    by other closed or concrete types.

    e.g.

    Returns true for Set[string] but false for Set or set
    '''
    if ttype is None:
        return False
    if ttype is typing.Set:
        return False
    if not hasattr(ttype, '__args__'):
        return False
    if ttype.__args__ is None or len(ttype.__args__) != 1:
        return False

    inner_type = ttype.__args__[0]
    origin = _get_origin(ttype)

    return (origin == typing.Set or origin is set) and not isinstance(inner_type, typing.TypeVar) 
开发者ID:dagster-io,项目名称:dagster,代码行数:24,代码来源:typing_api.py


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