Python typing.ClassVar() Examples

The following are 30 code examples of typing.ClassVar(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module typing , or try the search function .
Example #1
Source File: test_typing_inspect.py    From typing_inspect with MIT License 6 votes vote down vote up
def test_last_args(self):
        T = TypeVar('T')
        S = TypeVar('S')
        self.assertEqual(get_last_args(int), ())
        self.assertEqual(get_last_args(Union), ())
        if WITH_CLASSVAR:
            self.assertEqual(get_last_args(ClassVar[int]), (int,))
        self.assertEqual(get_last_args(Union[T, int]), (T, int))
        self.assertEqual(get_last_args(Union[str, int]), (str, int))
        self.assertEqual(get_last_args(Tuple[T, int]), (T, int))
        self.assertEqual(get_last_args(Tuple[str, int]), (str, int))
        self.assertEqual(get_last_args(Generic[T]), (T, ))
        if GENERIC_TUPLE_PARAMETRIZABLE:
            tp = Iterable[Tuple[T, S]][int, T]
            self.assertEqual(get_last_args(tp), (int, T))
        if LEGACY_TYPING:
            self.assertEqual(get_last_args(Callable[[T, S], int]), (T, S))
            self.assertEqual(get_last_args(Callable[[], int]), ())
        else:
            self.assertEqual(get_last_args(Callable[[T, S], int]), (T, S, int))
            self.assertEqual(get_last_args(Callable[[], int]), (int,)) 
Example #2
Source File: test_dataclasses.py    From android_universal with MIT License 6 votes vote down vote up
def test_other_params(self):
        C = make_dataclass('C',
                           [('x', int),
                            ('y', ClassVar[int], 10),
                            ('z', ClassVar[int], field(default=20)),
                            ],
                           init=False)
        # Make sure we have a repr, but no init.
        self.assertNotIn('__init__', vars(C))
        self.assertIn('__repr__', vars(C))

        # Make sure random other params don't work.
        with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):
            C = make_dataclass('C',
                               [],
                               xxinit=False) 
Example #3
Source File: test_dataclasses.py    From android_universal with MIT License 6 votes vote down vote up
def test_isnt_classvar(self):
        for typestr in ('CV',
                        't.ClassVar',
                        't.ClassVar[int]',
                        'typing..ClassVar[int]',
                        'Classvar',
                        'Classvar[int]',
                        'typing.ClassVarx[int]',
                        'typong.ClassVar[int]',
                        'dataclasses.ClassVar[int]',
                        'typingxClassVar[str]',
                        ):
            with self.subTest(typestr=typestr):
                @dataclass
                class C:
                    x: typestr

                # x is not a ClassVar, so C() takes one arg.
                self.assertEqual(C(10).x, 10) 
Example #4
Source File: test_dataclasses.py    From dataclasses with Apache License 2.0 6 votes vote down vote up
def test_isnt_classvar(self):
        for typestr in ('CV',
                        't.ClassVar',
                        't.ClassVar[int]',
                        'typing..ClassVar[int]',
                        'Classvar',
                        'Classvar[int]',
                        'typing.ClassVarx[int]',
                        'typong.ClassVar[int]',
                        'dataclasses.ClassVar[int]',
                        'typingxClassVar[str]',
                        ):
            with self.subTest(typestr=typestr):
                @dataclass
                class C:
                    x: typestr

                # x is not a ClassVar, so C() takes one arg.
                self.assertEqual(C(10).x, 10) 
Example #5
Source File: test_dataclasses.py    From dataclasses with Apache License 2.0 6 votes vote down vote up
def test_other_params(self):
        C = make_dataclass('C',
                           [('x', int),
                            ('y', ClassVar[int], 10),
                            ('z', ClassVar[int], field(default=20)),
                            ],
                           init=False)
        # Make sure we have a repr, but no init.
        self.assertNotIn('__init__', vars(C))
        self.assertIn('__repr__', vars(C))

        # Make sure random other params don't work.
        with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):
            C = make_dataclass('C',
                               [],
                               xxinit=False) 
Example #6
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_pickle(self):
        global C  # pickle wants to reference the class by name
        T = TypeVar('T')

        class B(Generic[T]):
            pass

        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'})
        simples = [Any, Union, Tuple, Callable, ClassVar, List, typing.Iterable]
        for s in simples:
            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
                z = pickle.dumps(s, proto)
                x = pickle.loads(z)
                self.assertEqual(s, x) 
Example #7
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
def __subclasscheck__(self, cls):
            raise TypeError("ClassVar cannot be used with issubclass().") 
Example #8
Source File: _model_utils.py    From flask-file-upload with GNU General Public License v3.0 5 votes vote down vote up
def get_by_postfix(model: ClassVar, filename: str, postfix: str) -> str:
        """
        :param model:
        :param filename:
        :param postfix:
        :return str:
        """
        return getattr(model, _ModelUtils.add_postfix(filename, postfix)) 
Example #9
Source File: _model_utils.py    From flask-file-upload with GNU General Public License v3.0 5 votes vote down vote up
def get_attr_from_model(wrapped: ClassVar, new_cols: List, file_names: List, db: Any) -> Any:
        """
        Adds values to new_cols & file_names so as not to
        change the size of the dict at runtime
        :return None:
        """
        for attr, value in wrapped.__dict__.items():
            if isinstance(value, Column):
                new_cols.append(_ModelUtils.columns_dict(attr, db))
                file_names.append(str(attr))
        return new_cols, file_names 
Example #10
Source File: _model_utils.py    From flask-file-upload with GNU General Public License v3.0 5 votes vote down vote up
def remove_unused_cols(wrapped: ClassVar,  filenames: Tuple[str]) -> None:
        """
        Removes the original named attributes
        (this could be a good place to store
         metadata in a dict for example...)
        :return:
        """
        for col_name in filenames:
            delattr(wrapped, col_name) 
Example #11
Source File: _model_utils.py    From flask-file-upload with GNU General Public License v3.0 5 votes vote down vote up
def set_columns(wrapped: ClassVar, new_cols: Tuple[Dict[str, Any]]) -> None:
        """
        Sets related file data to a SqlAlchemy Model
        :return:
        """
        for col_dict in new_cols:
            for k, v in col_dict.items():
                setattr(wrapped, k, v) 
Example #12
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
def __eq__(self, other):
            if not isinstance(other, ClassVar):
                return NotImplemented
            if self.__type__ is not None:
                return self.__type__ == other.__type__
            return self is other 
Example #13
Source File: test_dataclasses.py    From pydantic with MIT License 5 votes vote down vote up
def test_classvar():
    @pydantic.dataclasses.dataclass
    class TestClassVar:
        klassvar: ClassVar = "I'm a Class variable"
        x: int

    tcv = TestClassVar(2)
    assert tcv.klassvar == "I'm a Class variable" 
Example #14
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
def __instancecheck__(self, obj):
            raise TypeError("ClassVar cannot be used with isinstance().") 
Example #15
Source File: helpers.py    From mashumaro with Apache License 2.0 5 votes vote down vote up
def is_class_var(t):
    if PY_36:
        return (
            is_special_typing_primitive(t) and
            type(t).__name__ == '_ClassVar'
        )
    if PY_37 or PY_38:
        return get_type_origin(t) is typing.ClassVar
    else:
        raise NotImplementedError 
Example #16
Source File: dict_branch.py    From vkbottle with MIT License 5 votes vote down vote up
def cls_branch(
        self, branch_name: str = None,
    ):
        def decorator(cls: typing.ClassVar):
            self.names[branch_name or cls.__name__] = (
                cls,
                ImmutableBranchData(branch_name),
            )
            return cls

        return decorator 
Example #17
Source File: constructor.py    From vkbottle with MIT License 5 votes vote down vote up
def construct(self, *args, **kwargs) -> typing.ClassVar:
        """ Construct new object """
        pass 
Example #18
Source File: test_generics.py    From pydantic with MIT License 5 votes vote down vote up
def test_classvar():
    T = TypeVar('T')

    class Result(GenericModel, Generic[T]):
        data: T
        other: ClassVar[int] = 1

    assert Result.other == 1
    assert Result[int].other == 1
    assert Result[int](data=1).other == 1
    assert 'other' not in Result.__fields__ 
Example #19
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_no_isinstance(self):
        with self.assertRaises(TypeError):
            isinstance(1, ClassVar[int])
        with self.assertRaises(TypeError):
            issubclass(int, ClassVar) 
Example #20
Source File: test_main.py    From pydantic with MIT License 5 votes vote down vote up
def test_class_var():
    class MyModel(BaseModel):
        a: ClassVar
        b: ClassVar[int] = 1
        c: int = 2

    assert list(MyModel.__fields__.keys()) == ['c'] 
Example #21
Source File: test_dataclasses.py    From android_universal with MIT License 5 votes vote down vote up
def test_class_var(self):
        # Make sure ClassVars are ignored in __init__, __repr__, etc.
        @dataclass
        class C:
            x: int
            y: int = 10
            z: ClassVar[int] = 1000
            w: ClassVar[int] = 2000
            t: ClassVar[int] = 3000
            s: ClassVar      = 4000

        c = C(5)
        self.assertEqual(repr(c), 'TestCase.test_class_var.<locals>.C(x=5, y=10)')
        self.assertEqual(len(fields(C)), 2)                 # We have 2 fields.
        self.assertEqual(len(C.__annotations__), 6)         # And 4 ClassVars.
        self.assertEqual(c.z, 1000)
        self.assertEqual(c.w, 2000)
        self.assertEqual(c.t, 3000)
        self.assertEqual(c.s, 4000)
        C.z += 1
        self.assertEqual(c.z, 1001)
        c = C(20)
        self.assertEqual((c.x, c.y), (20, 10))
        self.assertEqual(c.z, 1001)
        self.assertEqual(c.w, 2000)
        self.assertEqual(c.t, 3000)
        self.assertEqual(c.s, 4000) 
Example #22
Source File: test_dataclasses.py    From android_universal with MIT License 5 votes vote down vote up
def test_class_var_no_default(self):
        # If a ClassVar has no default value, it should not be set on the class.
        @dataclass
        class C:
            x: ClassVar[int]

        self.assertNotIn('x', C.__dict__) 
Example #23
Source File: test_dataclasses.py    From android_universal with MIT License 5 votes vote down vote up
def test_class_var_default_factory(self):
        # It makes no sense for a ClassVar to have a default factory. When
        #  would it be called? Call it yourself, since it's class-wide.
        with self.assertRaisesRegex(TypeError,
                                    'cannot have a default factory'):
            @dataclass
            class C:
                x: ClassVar[int] = field(default_factory=int)

            self.assertNotIn('x', C.__dict__) 
Example #24
Source File: test_dataclasses.py    From android_universal with MIT License 5 votes vote down vote up
def test_class_var_with_default(self):
        # If a ClassVar has a default value, it should be set on the class.
        @dataclass
        class C:
            x: ClassVar[int] = 10
        self.assertEqual(C.x, 10)

        @dataclass
        class C:
            x: ClassVar[int] = field(default=10)
        self.assertEqual(C.x, 10) 
Example #25
Source File: test_dataclasses.py    From android_universal with MIT License 5 votes vote down vote up
def test_classvar_default_factory(self):
        # It's an error for a ClassVar to have a factory function.
        with self.assertRaisesRegex(TypeError,
                                    'cannot have a default factory'):
            @dataclass
            class C:
                x: ClassVar[int] = field(default_factory=int) 
Example #26
Source File: test_dataclasses.py    From android_universal with MIT License 5 votes vote down vote up
def test_classvar(self):
        # Some expressions recognized as ClassVar really aren't.  But
        #  if you're using string annotations, it's not an exact
        #  science.
        # These tests assume that both "import typing" and "from
        # typing import *" have been run in this file.
        for typestr in ('ClassVar[int]',
                        'ClassVar [int]'
                        ' ClassVar [int]',
                        'ClassVar',
                        ' ClassVar ',
                        'typing.ClassVar[int]',
                        'typing.ClassVar[str]',
                        ' typing.ClassVar[str]',
                        'typing .ClassVar[str]',
                        'typing. ClassVar[str]',
                        'typing.ClassVar [str]',
                        'typing.ClassVar [ str]',

                        # Not syntactically valid, but these will
                        #  be treated as ClassVars.
                        'typing.ClassVar.[int]',
                        'typing.ClassVar+',
                        ):
            with self.subTest(typestr=typestr):
                @dataclass
                class C:
                    x: typestr

                # x is a ClassVar, so C() takes no args.
                C()

                # And it won't appear in the class's dict because it doesn't
                # have a default.
                self.assertNotIn('x', C.__dict__) 
Example #27
Source File: test_dataclasses.py    From android_universal with MIT License 5 votes vote down vote up
def test_class_var(self):
        C = make_dataclass('C',
                           [('x', int),
                            ('y', ClassVar[int], 10),
                            ('z', ClassVar[int], field(default=20)),
                            ])
        c = C(1)
        self.assertEqual(vars(c), {'x': 1})
        self.assertEqual(len(fields(c)), 1)
        self.assertEqual(C.y, 10)
        self.assertEqual(C.z, 20) 
Example #28
Source File: _entity.py    From flask-jwt-router with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, extensions: ClassVar):
        self.extensions = extensions 
Example #29
Source File: test_typing_inspect.py    From typing_inspect with MIT License 5 votes vote down vote up
def test_classvar(self):
        T = TypeVar('T')
        samples = [ClassVar, ClassVar[int], ClassVar[List[T]]]
        nonsamples = [int, 42, Iterable, List[int], type, T]
        self.sample_test(is_classvar, samples, nonsamples) 
Example #30
Source File: test_dataclasses.py    From dataclasses with Apache License 2.0 5 votes vote down vote up
def test_class_var(self):
        # Make sure ClassVars are ignored in __init__, __repr__, etc.
        @dataclass
        class C:
            x: int
            y: int = 10
            z: ClassVar[int] = 1000
            w: ClassVar[int] = 2000
            t: ClassVar[int] = 3000
            s: ClassVar      = 4000

        c = C(5)
        self.assertEqual(repr(c), 'TestCase.test_class_var.<locals>.C(x=5, y=10)')
        self.assertEqual(len(fields(C)), 2)                 # We have 2 fields.
        self.assertEqual(len(C.__annotations__), 6)         # And 4 ClassVars.
        self.assertEqual(c.z, 1000)
        self.assertEqual(c.w, 2000)
        self.assertEqual(c.t, 3000)
        self.assertEqual(c.s, 4000)
        C.z += 1
        self.assertEqual(c.z, 1001)
        c = C(20)
        self.assertEqual((c.x, c.y), (20, 10))
        self.assertEqual(c.z, 1001)
        self.assertEqual(c.w, 2000)
        self.assertEqual(c.t, 3000)
        self.assertEqual(c.s, 4000)