import asyncio
import datetime
import json
import os
import re
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, assert_type
def check_int(x: int) -> None:
pass
def check_float(x: float) -> None:
pass
def check_str(x: str) -> None:
pass
def check_bool(x: bool) -> None:
pass
def check_bytes(x: bytes) -> None:
pass
def check_list_int(x: list[int]) -> None:
pass
def check_list_str(x: list[str]) -> None:
pass
def check_tuple_int(x: tuple[int, ...]) -> None:
pass
def check_dict_str_int(x: dict[str, int]) -> None:
pass
def check_set_int(x: set[int]) -> None:
pass
def check_frozenset_int(x: frozenset[int]) -> None:
pass
def get_int() -> int:
return 123
def get_float() -> float:
return 3.14
def get_str() -> str:
return 'hello'
def get_list_int() -> list[int]:
return [1, 2, 3]
def get_list_str() -> list[str]:
return ['a', 'b', 'c']
def get_object() -> object:
return object()
def get_dict_str_int() -> dict[str, int]:
return {'a': 1, 'b': 2}
def get_set_str() -> set[str]:
return {'a', 'b', 'c'}
def get_frozenset_str() -> frozenset[str]:
return frozenset({'a', 'b', 'c'})
def get_tuple_str_int() -> tuple[str, int]:
return ('hello', 42)
def get_bytes() -> bytes:
return b'hello'
obj = object()
t = type(42)
check_bool(True)
check_bool(False)
check_bool(bool(1))
check_bool(bool(''))
check_int(42)
check_int(int('42'))
check_int(int(3.14))
check_int(int(get_int()))
check_int(int(get_float()))
check_float(3.14)
check_float(float('3.14'))
check_float(float(42))
f = get_float()
assert_type(f, float)
check_str('hello')
check_str(str(42))
check_str(str(b'hello', 'utf-8'))
check_str(str(get_int()))
check_bytes(b'hello')
check_bytes(bytes('hello', 'utf-8'))
check_bytes(bytes(10))
check_bytes(bytes([65, 66, 67]))
check_bytes(bytes(get_int()))
k2 = get_bytes()
assert_type(k2, bytes)
check_list_int([1, 2, 3])
check_list_str(list('abc'))
check_list_int(list(range(10)))
m2 = get_list_int()
assert_type(m2, list[int])
m3 = get_list_str()
assert_type(m3, list[str])
check_tuple_int(tuple([1, 2, 3]))
p2 = get_tuple_str_int()
assert_type(p2, tuple[str, int])
check_dict_str_int({'a': 1, 'b': 2})
check_dict_str_int(dict(a=1, b=2))
d = get_dict_str_int()
assert_type(d, dict[str, int])
check_set_int({1, 2, 3})
check_set_int(set([1, 2, 3]))
check_frozenset_int(frozenset([1, 2, 3]))
w = range(get_int())
assert_type(w, range)
sl1 = slice(10)
sl2 = slice(0, 10)
sl3 = slice(0, 10, 2)
check_int(abs(-5))
check_float(abs(-3.14))
check_bool(all([True, False]))
check_bool(any([True, False]))
aa = all(get_list_int())
assert_type(aa, bool)
check_str(bin(42))
check_str(hex(255))
check_str(oct(8))
ac = bin(get_int())
assert_type(ac, str)
check_str(chr(65))
check_int(ord('A'))
af = chr(get_int())
assert_type(af, str)
ag = ord(get_str())
assert_type(ag, int)
dm = divmod(10, 3)
check_int(hash('hello'))
ai = hash(get_str())
assert_type(ai, int)
check_int(id(object()))
ak = id(get_object())
assert_type(ak, int)
check_bool(isinstance(42, int))
al = isinstance(get_object(), int)
assert_type(al, bool)
check_int(len([1, 2, 3]))
an = len(get_list_int())
assert_type(an, int)
check_int(max(1, 2, 3))
check_int(min(1, 2, 3))
check_int(pow(2, 3))
check_float(pow(2.0, 3.0))
aw = print(get_str())
assert_type(aw, None)
check_str(repr(42))
ax = repr(get_int())
assert_type(ax, str)
check_int(round(3.7))
check_list_int(sorted([3, 1, 2]))
check_int(sum([1, 2, 3]))
ba = sum(get_list_int())
assert_type(ba, int)
bf = type(get_int())
assert_type(bf, type[int])
for i_enum, v_enum in enumerate([1, 2, 3]):
check_int(i_enum)
check_int(v_enum)
for v_rev in reversed([1, 2, 3]):
check_int(v_rev)
for a_zip, b_zip in zip([1, 2], ['a', 'b']):
check_int(a_zip)
check_str(b_zip)
bk = None
assert_type(bk, None)
e1 = BaseException('error')
e2 = Exception('error')
e3 = SystemExit(1)
e4 = KeyboardInterrupt()
e5 = ArithmeticError('error')
e6 = OverflowError('error')
e7 = ZeroDivisionError('error')
e8 = LookupError('error')
e9 = IndexError('error')
e10 = KeyError('key')
e11 = RuntimeError('error')
e12 = NotImplementedError('error')
e13 = RecursionError('error')
e14 = AttributeError('error')
e15 = AssertionError('error')
e16 = MemoryError('error')
e17 = NameError('error')
e18 = SyntaxError('error')
e19 = TimeoutError('error')
e20 = TypeError('error')
e21 = ValueError('error')
e22 = StopIteration()
def handle_base(e: BaseException) -> None:
pass
handle_base(Exception('error'))
handle_base(ValueError('error'))
handle_base(KeyError('key'))
handle_base(ZeroDivisionError('error'))
def handle_exception(e: Exception) -> None:
pass
handle_exception(ValueError('error'))
handle_exception(TypeError('error'))
handle_exception(RuntimeError('error'))
try:
x_try = 1 / 0
except ZeroDivisionError as e_try:
check_str(str(e_try))
try:
d_try: dict[str, int] = {}
v_try = d_try['missing']
except KeyError:
pass
try:
lst_try: list[int] = []
v_lst = lst_try[0]
except IndexError:
pass
def may_fail(x_fail: int) -> int:
if x_fail < 0:
raise ValueError('x must be non-negative')
if x_fail == 0:
raise ZeroDivisionError('x cannot be zero')
return 100 // x_fail
def not_implemented() -> None:
raise NotImplementedError('subclass must implement')
print(sys.version)
print(sys.version_info)
print(None, file=sys.stdout)
print(None, file=sys.stderr)
async def foo(a: int):
return a * 2
async def bar():
await foo(1)
await foo(2)
await foo(3)
await asyncio.gather(bar())
asyncio.run(foo(1))
@dataclass
class Point:
x: int
y: float
p = Point(1, 2)
assert_type(p.x, int)
assert_type(p.y, float)
p.x = 3
print(p)
path = Path(__file__)
assert_type(path, Path)
p2 = path.parent
assert_type(p2, Path)
p3 = path / 'test.txt'
assert_type(p3, Path)
assert p3.name == 'test.txt'
x = os.getenv('foobar')
assert_type(x, str | None)
y = os.getenv('foobar', default=int('123'))
assert_type(y, str | int)
x2 = os.environ.get('foobar')
assert_type(x2, str | None)
s1 = re.search(r'\d+', 'abc 42')
assert_type(s1, re.Match[str] | None)
s2 = re.match(r'\w+', 'hello')
assert_type(s2, re.Match[str] | None)
s3 = re.fullmatch(r'\w+', 'hello')
assert_type(s3, re.Match[str] | None)
p_re = re.compile(r'\d+')
assert_type(p_re, re.Pattern[str])
fa = re.findall(r'\d+', 'a1 b2 c3')
assert_type(fa, list[Any])
s4 = re.sub(r'\d+', 'X', 'a1 b2')
assert_type(s4, str)
p_re2 = re.compile(r'(\w+)')
s5 = p_re2.search('hello world')
assert_type(s5, re.Match[str] | None)
s6 = p_re2.match('hello world')
assert_type(s6, re.Match[str] | None)
s7 = p_re2.sub('X', 'hello world')
assert_type(s7, str)
fa2 = p_re2.findall('hello world')
assert_type(fa2, list[Any])
dt_date = datetime.date(2024, 1, 15)
assert_type(dt_date, datetime.date)
check_int(dt_date.year)
check_int(dt_date.month)
check_int(dt_date.day)
check_str(dt_date.isoformat())
check_str(dt_date.strftime('%Y-%m-%d'))
check_int(dt_date.weekday())
check_int(dt_date.isoweekday())
check_int(dt_date.toordinal())
check_str(dt_date.ctime())
datetime.date.today()
datetime.date.fromisoformat('2024-01-15')
datetime.date.fromordinal(738900)
dt_replaced = dt_date.replace(year=2025)
assert_type(dt_replaced, datetime.date)
dt_delta = datetime.timedelta(days=1)
dt_date2 = dt_date + dt_delta
assert_type(dt_date2, datetime.date)
dt_diff = dt_date - dt_date
assert_type(dt_diff, datetime.timedelta)
dt_time = datetime.time(12, 30, 45)
assert_type(dt_time, datetime.time)
check_int(dt_time.hour)
check_int(dt_time.minute)
check_int(dt_time.second)
check_int(dt_time.microsecond)
check_str(dt_time.isoformat())
check_str(dt_time.strftime('%H:%M:%S'))
dt_time2 = dt_time.replace(hour=14)
assert_type(dt_time2, datetime.time)
td = datetime.timedelta(days=5, hours=3, minutes=30)
assert_type(td, datetime.timedelta)
check_int(td.days)
check_int(td.seconds)
check_int(td.microseconds)
check_float(td.total_seconds())
td2 = td + td
assert_type(td2, datetime.timedelta)
td3 = td - td
assert_type(td3, datetime.timedelta)
td4 = td * 2
assert_type(td4, datetime.timedelta)
dt = datetime.datetime(2024, 1, 15, 12, 30, 45)
assert_type(dt, datetime.datetime)
check_int(dt.year)
check_int(dt.month)
check_int(dt.day)
check_int(dt.hour)
check_int(dt.minute)
check_int(dt.second)
check_int(dt.microsecond)
check_str(dt.isoformat())
check_str(dt.strftime('%Y-%m-%d %H:%M:%S'))
check_float(dt.timestamp())
dt_d = dt.date()
assert_type(dt_d, datetime.date)
dt_t = dt.time()
assert_type(dt_t, datetime.time)
datetime.datetime.now()
datetime.datetime.strptime('2024-01-15', '%Y-%m-%d')
datetime.datetime.fromtimestamp(1000000.0)
dt_rep = dt.replace(year=2025)
assert_type(dt_rep, datetime.datetime)
utc = datetime.timezone.utc
assert_type(utc, datetime.timezone)
tz = datetime.timezone(datetime.timedelta(hours=5))
assert_type(tz, datetime.timezone)
assert_type(json.loads('null'), Any)
assert_type(json.dumps(None), str)
it = iter([1, 2, 3])
next(it)
next(it, 0)
list(it)
for _x in iter([1, 2, 3]):
pass
list(iter(lambda: 0, 0))