Skip to content

Instantly share code, notes, and snippets.

@luizamboni
Last active October 21, 2021 00:15
Show Gist options
  • Save luizamboni/fceba8f59e85f4e44de4af0195c705be to your computer and use it in GitHub Desktop.
Save luizamboni/fceba8f59e85f4e44de4af0195c705be to your computer and use it in GitHub Desktop.
artigo medium
import asyncio
from typing import Awaitable
async def mock_query(n: int) -> str:
print(f'chamada: {n}')
await asyncio.sleep(n)
return f'resultado da api chamada: {n}'
async def main() -> None:
result = await mock_query(1)
print(result)
exec: Awaitable[str] = mock_query(2)
result = await exec
print(result)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
d: int = 1
def half(d: int) -> float:
return d / 2
d = 1
def half(d):
return d / 2
from typing import Union, Callable
def multiply(d: int, m: Union[int, str]) -> float:
return d * float(m)
MathOp = Callable[[int, float], float]
def run_op(f: MathOp, a: float, b: float) -> float:
return f(a,b)
from typing import List
class Message:
# it will broke: use type between '' to forward bind Type when Queue already exist
# queue: Queue
queue: 'Queue'
content: str
def __init__(self, content: str) -> None:
self.content = content
# it will broke: use type between '' to forward bind Type when Queue already exist
# def bind_queue(self, queue: Queue) -> None:
def bind_queue(self, queue: 'Queue') -> None:
self.queue = queue
class Queue:
messages: List[Message]
def __init__(self, unbound_messages: List[Message]) -> None:
self.messages = unbound_messages
for message in self.messages:
message.bind_queue(self)
def hello(name):
print(f"hello {name}")
def hello(name: str) -> None: ...
[mypy]
check_untyped_defs = True
ignore_errors = False
ignore_missing_imports = True
strict_optional = True
from typing import Protocol, runtime_checkable
@runtime_checkable
class SupportPrint(Protocol):
def print(self, arg: str) -> None:
pass
class Logger:
logger: SupportPrint
def __init__(self, logger: SupportPrint) -> None:
logger.print(__name__)
class StdPrint:
def print(self, arg: str) -> None:
print(f"printing: {arg}")
intance = StdPrint()
print(
"is instance a SupportPrint",
isinstance(intance, SupportPrint)
)
{
"python.linting.mypyEnabled": true,
"python.linting.enabled": true
}
from typing import TypedDict
# User é um dicionário em que cada campo pode ter um valor tipo diferent,
# se todos os campos fossem do mesmo tipo, como por exemplo "str", bastaria uma definição usando a anotação "Dict[str,str]"
class User(TypedDict):
id: int
name: str
document: str
def get_user(id: int) -> User:
return {
"id": 12,
"name": "helena",
"document": "111.111.111-11",
}
from typing import Optional, Union
# não quero me preocupar se phone_number é um "int" ou um "str"
def print_phone(phone_number: Union[str,int]):
print(f"{phone_number}")
def print_phone_with_ddd(phone_number: Union[str, int], ddd: Optional[int]):
if ddd:
print(f"{ddd} {phone_number}")
else:
print_phone(phone_number)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment