python-typing

Dynamic checking of type hints in Python 3.5+ [duplicate]

◇◆丶佛笑我妖孽 提交于 2020-08-25 06:30:56
问题 This question already has answers here : How to use type hints in python 3.6? (3 answers) Closed 13 days ago . The typing module implements type hints in Python 3.5+. However, this is not enforced, it seems to currently only exist for the benefit of static type checkers such as mypy and PyCharm. I was hoping it would be a viable alternative to duck typing. Question : Is there a way to turn on dynamic type checking in Python 3.7+ that I didn't find in Google search? So for example, if I define

Python type hints with imported class methods

若如初见. 提交于 2020-08-10 19:53:45
问题 In order to split a large class into multiple files, this answer, recommends using the import command at the class level to load methods whose definitions can be moved to other modules. As a minimal example, class_def.py : class C: from _methods import m _methods.py : def m(self): return "hello" Normally, most IDEs which feature code completion will recognize functions which are defined in some class as bound methods, and self will automatically be recognized as having the type of the class

python typing signature (typing.Callable) for function with kwargs

你。 提交于 2020-07-28 09:26:06
问题 I heavily use python typing support from python 3. Recently I was trying to pass a function as an argument and I do not find any help for using kwargs in typing.Callable signature. Please check the code below and the comments. import typing # some function with singnature typing def fn1_as_arg_with_kwargs(a: int, b: float) -> float: return a + b # some function with singnature typing def fn2_as_arg_with_kwargs(a: int, b: float) -> float: return a * b # function that get callables as arg #

How can I add python type annotations to the flask global context g?

江枫思渺然 提交于 2020-07-06 09:41:24
问题 I have a decorator which adds a user onto the flask global context g: class User: def __init__(self, user_data) -> None: self.username: str = user_data["username"] self.email: str = user_data["email"] def login_required(f): @wraps(f) def wrap(*args, **kwargs): user_data = get_user_data() user = User(user_data) g.user = User(user_data) return f(*args, **kwargs) return wrap I want the type (User) of g.user to be known when I access g.user in the controllers. How can I achieve this? (I am using

Python typing: return type with generics like Clazz[T] as in Java Clazz<T>

我只是一个虾纸丫 提交于 2020-06-27 16:53:32
问题 So I am aware of pythons typing.Optional. But I wrote my own crude PyOptional (https://github.com/felixhertrampf/PyOptional/blob/master/PyOptional.py) and would like to combine Optional[T] with my PyOptional to PyOptional[T]. I am currently using Python 3.7 and tried extending typing.Optional. Some of my PyOptional class PyOptional: T: TypeVar = TypeVar("T") def __init__(self, obj: T): self.value: Any = obj def get(self) -> Optional[T]: return self.value def or_else(self, default) -> T:

Weird MRO result when inheriting directly from typing.NamedTuple

久未见 提交于 2020-05-29 04:07:27
问题 I am confused why FooBar.__mro__ doesn't show <class '__main__.Parent'> like the above two. I still don't know why after some digging into the CPython source code. from typing import NamedTuple from collections import namedtuple A = namedtuple('A', ['test']) class B(NamedTuple): test: str class Parent: pass class Foo(Parent, A): pass class Bar(Parent, B): pass class FooBar(Parent, NamedTuple): pass print(Foo.__mro__) # prints (<class '__main__.Foo'>, <class '__main__.Parent'>, <class '__main_

Python typing for a subclass of list

≡放荡痞女 提交于 2020-05-27 06:17:20
问题 I want to be able to define what the contents of a subclass of list have to be. The class would look like the following. class A(list): def __init__(self): list.__init__(self) I want to include typing such that the following would happen. import typing class A(list: typing.List[str]): # Maybe something like this def __init__(self): list.__init__(self) >> a = A() >> a.append("a") # No typing error >> a.append(1) # Typing error 回答1: typing conveniently provides a generic version of collections

Python 3 type hints in Python 2

岁酱吖の 提交于 2020-02-16 08:23:13
问题 I have python def definition which seems working for python3: def get_default_device(use_gpu: bool = True) -> cl.Device: Under python2 I get the following syntax error: root:~/pyopencla/ch3# python map_copy.py Traceback (most recent call last): File "map_copy.py", line 9, in <module> import utility File "/home/root/pyopencla/ch3/utility.py", line 6 def get_default_device(use_gpu: bool = True) -> cl.Device: ^ SyntaxError: invalid syntax How to make type hints compatible with python2? 回答1:

Exclude type in Python typing annotation

旧时模样 提交于 2020-01-30 05:44:18
问题 I wrote the following function: def _clean_dict(d): return {k: v for k, v in d.items() if v is not None} I want to add type annotations to the function: def _clean_dict(d: Dict[Any, Any]) -> Dict[Any, Any]: return {k: v for k, v in d.items() if v is not None} However, I want to explicitly define that the values inside the returned dictionary cannot be None. Is there a way to say " Any type, except NoneType " or "Every possible value but None "? 回答1: Python type hinting can't exclude types.

How to reference static method from class variable [duplicate]

人盡茶涼 提交于 2020-01-11 09:08:13
问题 This question already has answers here : Accessing class variables from a list comprehension in the class definition (5 answers) Closed 16 days ago . Given the class from __future__ import annotations from typing import ClassVar, Dict, Final import abc class Cipher(abc.ABC): @abc.abstractmethod def encrypt(self, plaintext: str) -> str: pass @abc.abstractmethod def decrypt(self, ciphertext: str) -> str: pass class VigenereCipher(Cipher): @staticmethod def rotate(n: int) -> str: return string