# Python Syntax Test # All of this file is (or should be) valid python syntax # This file is not semantically valid # Segments are written by Kyler or (mostly) from python docs import foo import foo.bar.baz import foo.bar.baz as fbb from foo.bar import baz from foo import attr def func(): if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1 month_names = ['Januari', 'Februari', 'Maart', # These are the 'April', 'Mei', 'Juni', # Dutch names 'Juli', 'Augustus', 'September', # for the months 'Oktober', 'November', 'December'] # of the year # Here is an example of a correctly (though confusingly) # indented piece of Python code: def perm(l): # Compute the list of all permutations of l if len(l) <= 1: return [l] r = [] for i in range(len(l)): s = l[:i] + l[i+1:] p = perm(s) for x in p: r.append(l[i:i+1] + x) return r def perm2(l): if len(l) <= 1: return [l] r = [] for i in range(len(l)): s = l[:i] + l[i+1:] p = perm(l[:i] + l[i+1:]) for x in p: r.append(l[i:i+1] + x) return r 'This string will not include \ backslashes or newline characters.' re.compile("[A-Za-z_]" # letter or underscore "[A-Za-z0-9_]*" # letter, digit or underscore ) # Some examples of formatted string literals: name = "Fred" f"He said his name is {name!r}." f"He said his name is {repr(name)}." # repr() is equivalent to !r width = 10 precision = 4 value = decimal.Decimal("12.34567") f"result: {value:{width}.{precision}}" # nested fields today = datetime(year=2017, month=1, day=27) f"{today:%B %d, %Y}" # using date format specifier f"{today=:%B %d, %Y}" # using date format specifier and debugging number = 1024 f"{number:#0x}" # using integer format specifier foo = "bar" f"{ foo = }" # preserves whitespace line = "The mill's closed" f"{line = }" f"{line = :20}" f"{line = !r:20}" newline = ord('\n') f"newline: {newline}" def foo(): f"Not a docstring" foo.__doc__ is None # Triple and Multiline """Test" test""" """test # test test""" r"hello\" world" rb"hello\" world" b"test" "hello\" world" # Some examples of integer literals: 7 2147483647 0o177 0b100110111 3 79228162514264337593543950336 0o377 0xdeadbeef 100_000_000_000 0b_1110_0101 # Some examples of floating point literals: 3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93 # Some examples of imaginary literals: 3.14j 10.j 10j .001j 1e100j 3.14e-10j 3.14_15_93j if x < y < z: print(x); print(y); print(z) print(sys.exception()) try: raise TypeError except: print(repr(sys.exception())) try: raise ValueError except: print(repr(sys.exception())) print(repr(sys.exception())) try: raise ExceptionGroup("eg", [ValueError(1), TypeError(2), OSError(3), OSError(4)]) except* TypeError as e: print(f'caught {type(e)} with nested {e.exceptions}') except* OSError as e: print(f'caught {type(e)} with nested {e.exceptions}') try: raise BlockingIOError except* BlockingIOError as e: print(repr(e)) # The return value of a function is determined by the last return statement executed def foo(): try: return 'try' finally: return 'finally' with EXPRESSION as TARGET: SUITE with A() as a, B() as b: SUITE with A() as a: with B() as b: SUITE with ( A() as a, B() as b, ): SUITE match = 1 case = 1 flag = False match (100, 200): case (100, 300): # Mismatch: 200 != 300 print('Case 1') case (100, 200) if flag: # Successful match, but guard fails print('Case 2') case (100, y): # Matches and binds y to 200 print(f'Case 3, y: {y}') case _: # Pattern not attempted print('Case 4, I match anything!') @f1(arg) @f2 def func(): pass def whats_on_the_telly(penguin=None): if penguin is None: penguin = [] penguin.append("property of the zoo") return penguin async def func(param1, param2): do_stuff() await some_coroutine() async for TARGET in ITER: SUITE else: SUITE2 async with EXPRESSION as TARGET: SUITE class Foo: pass class Foo(object): pass @f1(arg) @f2 class Foo: pass x = lambda o: o + 1 expr1, expr2, expr3, expr4 (expr1, expr2, expr3, expr4) {expr1: expr2, expr3: expr4} expr1 + expr2 * (expr3 - expr4) expr1(expr2, expr3, *expr4, **expr5) expr3, expr4 = expr1, expr2 if matching := pattern.search(data): do_something(matching) while chunk := file.read(9000): process(chunk) def f(a, b): print(a, b) f(b=1, *(2,)) f(a=1, *(2,)) f(1, *(2,)) def echo(value=None): print("Execution starts when 'next()' is called for the first time.") try: while True: try: value = (yield value) except Exception as e: value = e finally: print("Don't forget to clean up when 'close()' is called.") generator = echo(1) print(next(generator)) print(next(generator)) print(generator.send(2)) generator.throw(TypeError, "spam") generator.close() class Cls: x = 3 inst = Cls() inst.x = inst.x + 1 a, b = b, a x = [0, 1] i = 0 i, x[i] = 1, 2 print(x) def f(arg): pass try: print(1 / 0) except: raise RuntimeError("Something bad happened") try: print(1 / 0) except Exception as exc: raise RuntimeError("Something bad happened") from exc # Exception chaining can be explicitly suppressed by # specifying None in the from clause: try: print(1 / 0) except: raise RuntimeError("Something bad happened") from None def test(): yield -1 yield from range(10) def m(): module = None if spec.loader is not None and hasattr(spec.loader, 'create_module'): # It is assumed 'exec_module' will also be defined on the loader. module = spec.loader.create_module(spec) if module is None: module = ModuleType(spec.name) # The import-related module attributes get set here: _init_module_attrs(spec, module) if spec.loader is None: # unsupported raise ImportError if spec.origin is None and spec.submodule_search_locations is not None: # namespace package sys.modules[spec.name] = module elif not hasattr(spec.loader, 'exec_module'): module = spec.loader.load_module(spec.name) # Set __loader__ and __package__ if missing. else: sys.modules[spec.name] = module try: spec.loader.exec_module(module) except BaseException: try: del sys.modules[spec.name] except KeyError: pass raise return sys.modules[spec.name] class A: a = 42 b = list(a + i for i in range(10)) i = 10 def f(): print(i) i = 42 f() def all(iterable): for element in iterable: if not element: return False return True def any(iterable): for element in iterable: if element: return True return False class C: @classmethod def f(cls, arg1, arg2): ... import struct dir() # show the names in the module namespace dir(struct) # show the names in the struct module class Shape: def __dir__(self): return ['area', 'perimeter', 'location'] s = Shape() dir(s) seasons = ['Spring', 'Summer', 'Fall', 'Winter'] list(enumerate(seasons)) list(enumerate(seasons, start=1)) def enumerate(iterable, start=0): n = start for elem in iterable: yield n, elem n += 1 x = 1 eval('x+1') float('+1.23') float(' -12345\n') float('1e-003') float('+1E6') float('-Infinity') hex(255) hex(-42) '%#x' % 255, '%x' % 255, '%X' % 255 format(255, '#x'), format(255, 'x'), format(255, 'X') f'{255:#x}', f'{255:x}', f'{255:X}' s = input('--> ') from functools import partial with open('mydata.db', 'rb') as f: for block in iter(partial(f.read, 64), b''): process_block(block) oct(8) oct(-56) '%#o' % 10, '%o' % 10 format(10, '#o'), format(10, 'o') f'{10:#o}', f'{10:o}' import os dir_fd = os.open('somedir', os.O_RDONLY) def opener(path, flags): return os.open(path, flags, dir_fd=dir_fd) with open('spamspam.txt', 'w', opener=opener) as f: print('This will be written to somedir/spamspam.txt', file=f) os.close(dir_fd) # don't leak a file descriptor pow(38, -1, mod=97) 23 * 38 % 97 == 1 class C: def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage class C: def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x class C: @staticmethod def f(arg1, arg2, argN): ... def regular_function(): ... class C: method = staticmethod(regular_function) class C(B): def method(self, arg): super().method(arg) # This does the same thing as: # super(C, self).method(arg) class X: a = 1 X = type('X', (), dict(a=1)) for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']): print(item) list(zip(range(3), ['fee', 'fi', 'fo', 'fum'])) list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True)) x = [1, 2, 3] y = [4, 5, 6] list(zip(x, y)) x2, y2 = zip(*zip(x, y)) x == list(x2) and y == list(y2) import spam spam = __import__('spam', globals(), locals(), [], 0) import spam.ham spam = __import__('spam.ham', globals(), locals(), [], 0) from spam.ham import eggs, sausage as saus _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) eggs = _temp.eggs saus = _temp.sausage