當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。