├── README.md ├── advancedthread └── __main__.py ├── asyncio_advancedtask └── __main__.py ├── asyncio_basic └── __main__.py ├── asyncio_task └── __main__.py ├── classdecorator └── __main__.py ├── closure └── __main__.py ├── contextmanager └── __main__.py ├── dataclass └── __main__.py ├── decorator └── __main__.py ├── generator └── __main__.py ├── metaclass └── __main__.py ├── metaclass_sample └── __main__.py ├── mixin └── __main__.py ├── multiprocesses └── __main__.py ├── nonlocal └── __main__.py ├── processpool └── __main__.py ├── regex └── __main__.py ├── singleton └── __main__.py ├── threadlock └── __main__.py ├── threadpool └── __main__.py ├── threads └── __main__.py ├── typeclass └── __main__.py ├── variablescope └── __main__.py └── yield_from └── __main__.py /README.md: -------------------------------------------------------------------------------- 1 | # python_advance 2 | -------------------------------------------------------------------------------- /advancedthread/__main__.py: -------------------------------------------------------------------------------- 1 | import time 2 | from threading import Thread 3 | from queue import Queue 4 | 5 | 6 | class MyThread(Thread): 7 | def __init__(self, name: str, count: int): 8 | super().__init__() 9 | 10 | self.setName(name) 11 | self.setDaemon(True) 12 | self.count = count 13 | 14 | def run(self) -> None: 15 | for n in range(self.count): 16 | print(f"{self.getName()} - {n}\n", end='') 17 | time.sleep(0.01) 18 | 19 | 20 | t_1 = MyThread("A", 10) 21 | t_2 = MyThread("B", 10) 22 | 23 | t_1.start() 24 | t_2.start() 25 | 26 | t_1.join() 27 | 28 | 29 | class MsgProducer(Thread): 30 | def __init__(self, name: str, count: int, queue: Queue): 31 | super().__init__() 32 | 33 | self.setName(name) 34 | self.count = count 35 | self.queue = queue 36 | 37 | def run(self) -> None: 38 | for n in range(self.count): 39 | msg = f"{self.getName()} - {n}" 40 | self.queue.put(msg, block=True) 41 | 42 | 43 | class MsgConsumer(Thread): 44 | def __init__(self, name: str, queue: Queue): 45 | super().__init__() 46 | 47 | self.setName(name) 48 | self.queue = queue 49 | self.setDaemon(True) 50 | 51 | def run(self) -> None: 52 | while True: 53 | msg = self.queue.get(block=True) 54 | print(f"{self.getName()} - {msg}\n", end='') 55 | 56 | 57 | queue = Queue(3) 58 | threads = list() 59 | threads.append(MsgProducer("PA", 10, queue)) 60 | threads.append(MsgProducer("PB", 10, queue)) 61 | threads.append(MsgProducer("PC", 10, queue)) 62 | 63 | threads.append(MsgConsumer("CA", queue)) 64 | threads.append(MsgConsumer("CB", queue)) 65 | 66 | for t in threads: 67 | t.start() 68 | 69 | 70 | -------------------------------------------------------------------------------- /asyncio_advancedtask/__main__.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from asyncio.exceptions import TimeoutError 3 | 4 | 5 | async def play_music(music: str): 6 | print(f"Start playing {music}") 7 | await asyncio.sleep(3) 8 | print(f"Finished playing {music}") 9 | 10 | return music 11 | 12 | 13 | async def call_api(): 14 | print("calling api.....") 15 | raise Exception("Error calling") 16 | 17 | 18 | async def my_cancel(): 19 | task = asyncio.create_task(play_music("A")) 20 | 21 | await asyncio.sleep(3) 22 | 23 | if not task.done(): 24 | task.cancel() 25 | 26 | 27 | async def my_cancel_with_timeout(): 28 | task = asyncio.create_task(play_music("B")) 29 | 30 | try: 31 | await asyncio.wait_for(task, timeout=2) 32 | except TimeoutError: 33 | print("timeout") 34 | 35 | 36 | async def my_timeout(): 37 | task = asyncio.create_task(play_music("B")) 38 | 39 | try: 40 | await asyncio.wait_for(asyncio.shield(task), timeout=2) 41 | except TimeoutError: 42 | print("timeout") 43 | await task 44 | 45 | 46 | async def my_gather(): 47 | results = await asyncio.gather(play_music("A"), play_music("B")) 48 | print(results) 49 | 50 | 51 | async def my_gather_with_exception(): 52 | results = await asyncio.gather(play_music("A"), play_music("B"), call_api(), 53 | return_exceptions=True) 54 | print(results) 55 | 56 | if __name__ == "__main__": 57 | asyncio.run(my_gather_with_exception()) 58 | -------------------------------------------------------------------------------- /asyncio_basic/__main__.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | 3 | 4 | async def calculate(n_1: int, n_2: int): 5 | res = n_1 + n_2 6 | print(res) 7 | 8 | 9 | async def main(): 10 | print("main -step 1") 11 | await calculate(1, 2) 12 | print("main -step 2") 13 | 14 | 15 | asyncio.run(main()) 16 | -------------------------------------------------------------------------------- /asyncio_task/__main__.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import time 3 | 4 | 5 | async def call_api(name: str, delay: float): 6 | print(f"{name} - step 1") 7 | await asyncio.sleep(delay) 8 | print(f"{name} - step 2") 9 | 10 | 11 | async def main(): 12 | time_1 = time.perf_counter() 13 | print("start A coroutine") 14 | task_1 = asyncio.create_task(call_api("A", 2)) 15 | 16 | print("start B coroutine") 17 | task_2 = asyncio.create_task(call_api("B", 5)) 18 | 19 | await task_1 20 | print("task 1 completed") 21 | await task_2 22 | print("task 2 completed") 23 | 24 | time_2 = time.perf_counter() 25 | print(f"Spent {time_2 - time_1}") 26 | 27 | 28 | asyncio.run(main()) 29 | -------------------------------------------------------------------------------- /classdecorator/__main__.py: -------------------------------------------------------------------------------- 1 | class MyDecorator: 2 | def __init__(self, f): 3 | self.f = f 4 | 5 | def __call__(self, *args, **kwargs): 6 | print("start") 7 | result = self.f(*args, **kwargs) 8 | print("end") 9 | return result 10 | 11 | 12 | class ParamDecorator: 13 | def __init__(self, name): 14 | self.name = name 15 | 16 | def __call__(self, f): 17 | def wrap(*args): 18 | print(f"start {self.name}") 19 | result = f(*args) 20 | print("end") 21 | return result 22 | 23 | return wrap 24 | 25 | 26 | @ParamDecorator("Jack") 27 | def test(): 28 | print("test") 29 | return 200 30 | 31 | 32 | print(test()) 33 | 34 | 35 | def cls_decorator(cls): 36 | print("start class decorator") 37 | 38 | def inner(): 39 | print("start") 40 | obj = cls() 41 | print("end") 42 | return obj 43 | 44 | return inner 45 | 46 | 47 | @cls_decorator 48 | class Person: 49 | pass 50 | 51 | p1 = Person() 52 | p2 = Person() 53 | -------------------------------------------------------------------------------- /closure/__main__.py: -------------------------------------------------------------------------------- 1 | def greeting(): 2 | message = "hello" 3 | value = 20 4 | 5 | def inner(): 6 | print(f'{value} - {message}') 7 | 8 | message = "second" 9 | 10 | return inner 11 | 12 | 13 | f = greeting() 14 | print(f.__closure__) 15 | f() 16 | -------------------------------------------------------------------------------- /contextmanager/__main__.py: -------------------------------------------------------------------------------- 1 | # instance = open("mydata.txt", "w") 2 | # instance.write("Hello this is a test file") 3 | # instance.close() 4 | 5 | # with open("mydata.txt", "w") as instance: 6 | # instance.write("Hello this is a test file") 7 | # 8 | # 9 | # print("The end") 10 | import time 11 | 12 | 13 | class Timer: 14 | def __init__(self): 15 | self.elapsed = 0 16 | 17 | def __enter__(self): 18 | self.start = time.perf_counter() 19 | return self 20 | 21 | def __exit__(self, exc_type, exc_val, exc_tb): 22 | self.stop = time.perf_counter() 23 | self.elapsed = self.stop - self.start 24 | return False 25 | 26 | 27 | with Timer() as timer: 28 | nums = [] 29 | for n in range(10000): 30 | nums.append(n ** 2) 31 | 32 | print(timer.elapsed) 33 | 34 | 35 | -------------------------------------------------------------------------------- /dataclass/__main__.py: -------------------------------------------------------------------------------- 1 | import operator 2 | from dataclasses import dataclass, field 3 | 4 | 5 | @dataclass(order=True) 6 | class Student: 7 | sort_index: int = field(init=False, repr=False) 8 | 9 | name: str 10 | age: int = 19 11 | independent: bool = field(default=False, init=False, repr=True) 12 | 13 | def __post_init__(self): 14 | self.independent = self.age > 19 15 | self.sort_index = self.age 16 | 17 | 18 | s_1 = Student("Jack", 20) 19 | print(s_1) 20 | 21 | s_2 = Student("Tom") 22 | print(s_2) 23 | 24 | print(s_1 == s_2) 25 | 26 | students = [s_2, s_1] 27 | sorted_students = sorted(students) 28 | print(sorted_students) 29 | 30 | students.sort(key=operator.attrgetter('name')) 31 | print(students) 32 | -------------------------------------------------------------------------------- /decorator/__main__.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | 3 | 4 | # def welcome(fn): 5 | # @wraps(fn) 6 | # def wrapper(*args, **kwargs): 7 | # print("Welcome") 8 | # result = fn(*args, **kwargs) 9 | # return result 10 | # 11 | # return wrapper 12 | 13 | def welcome(name): 14 | def decorator(fn): 15 | @wraps(fn) 16 | def wrapper(*args, **kwargs): 17 | print(f"Welcome {name}") 18 | result = fn(*args, **kwargs) 19 | return result 20 | 21 | return wrapper 22 | return decorator 23 | 24 | 25 | @welcome("Tom") 26 | def my_fun(message: str): 27 | print(f"Hello {message}") 28 | 29 | 30 | @welcome("Mary") 31 | def my_fun_2(): 32 | print("my fun 2") 33 | 34 | 35 | # f1 = welcome(my_fun) 36 | # f1("Jack") 37 | 38 | my_fun("Jack") 39 | 40 | print(my_fun.__name__) 41 | -------------------------------------------------------------------------------- /generator/__main__.py: -------------------------------------------------------------------------------- 1 | def hello(): # an iteratable object 2 | print("step 1") 3 | yield 1 4 | print("step 2") 5 | yield 2 6 | print("step 3") 7 | yield 3 8 | 9 | 10 | def my_fun(): 11 | result = [] 12 | for n in range(3): 13 | result.append(n ** 2) 14 | 15 | return result 16 | 17 | 18 | g = hello() 19 | for res in g: 20 | print(res) 21 | 22 | 23 | def squares(count: int): 24 | for n in range(count): 25 | yield n ** 2 26 | 27 | 28 | for num in squares(3): 29 | print(num) 30 | -------------------------------------------------------------------------------- /metaclass/__main__.py: -------------------------------------------------------------------------------- 1 | class Human(type): 2 | @staticmethod 3 | def __new__(mcs, *args, **kwargs): 4 | class_ = super().__new__(mcs, *args) 5 | # class_.freedom = True 6 | if kwargs: 7 | for name, value in kwargs.items(): 8 | setattr(class_, name, value) 9 | return class_ 10 | 11 | 12 | class Student(object, metaclass=Human, country="China", freedom=True): 13 | pass 14 | 15 | 16 | print(Student.country) 17 | print(Student.freedom) 18 | -------------------------------------------------------------------------------- /metaclass_sample/__main__.py: -------------------------------------------------------------------------------- 1 | class Prop: 2 | def __init__(self, attr): 3 | self._attr = f'_{attr}' 4 | 5 | def get(self, obj): 6 | if not hasattr(obj, self._attr): 7 | return None 8 | 9 | return getattr(obj, self._attr) 10 | 11 | def set(self, obj, value): 12 | setattr(obj, self._attr, value) 13 | 14 | 15 | class Human(type): 16 | @staticmethod 17 | def __new__(mcs, *args, **kwargs): 18 | class_ = super().__new__(mcs, *args) 19 | for property_name in class_.props: 20 | prop = Prop(property_name) 21 | p_obj = property(fget=prop.get, fset=prop.set) 22 | setattr(class_, property_name, p_obj) 23 | 24 | return class_ 25 | 26 | 27 | class Student(object, metaclass=Human): 28 | props = ["name", "age"] 29 | 30 | 31 | def human(cls): 32 | return Human(cls.__name__, cls.__bases__, dict(cls.__dict__)) 33 | 34 | 35 | @human 36 | class Man: 37 | props = ["name", "age"] 38 | 39 | 40 | man = Man() 41 | print(man.name) 42 | man.name = "Tom" 43 | print(man.name) 44 | 45 | 46 | student = Student() 47 | print(student.name) 48 | student.name = "Jack" 49 | print(student.name) 50 | -------------------------------------------------------------------------------- /mixin/__main__.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | 4 | class MapMixin: 5 | def __getitem__(self, key): 6 | return self.__dict__[key] 7 | 8 | def __setitem__(self, key, value): 9 | self.__dict__[key] = value 10 | 11 | 12 | class DictMixin: 13 | def to_dict(self): 14 | return self.__convert_dict(self.__dict__) 15 | 16 | def __convert_dict(self, attrs: dict): 17 | result = {} 18 | for key, value in attrs.items(): 19 | result[key] = self.__convert_value(value) 20 | 21 | return result 22 | 23 | def __convert_value(self, value): 24 | if isinstance(value, DictMixin): 25 | return value.to_dict() 26 | elif isinstance(value, dict): 27 | return self.__convert_dict(value) 28 | elif isinstance(value, list): 29 | return [self.__convert_value(v) for v in value] 30 | elif hasattr(value, '__dict__'): 31 | return self.__convert_dict(value.__dict__) 32 | else: 33 | return value 34 | 35 | 36 | class JSONMixin: 37 | def to_json(self): 38 | return json.dumps(self.to_dict()) 39 | 40 | 41 | class Student(MapMixin, DictMixin, JSONMixin): 42 | def __init__(self, name, age): 43 | self.name = name 44 | self.age = age 45 | 46 | # {"name": "Jack", "age": 20, "clasx": {"name": "class 9-1", "building": "A"}} 47 | 48 | s = Student("Jack", 20) 49 | 50 | print(s["name"]) 51 | print(s.to_dict()) 52 | print(s.to_json()) 53 | 54 | -------------------------------------------------------------------------------- /multiprocesses/__main__.py: -------------------------------------------------------------------------------- 1 | import multiprocessing 2 | import time 3 | 4 | 5 | def task(name: str, count: int): 6 | print(f"{name} - start\n", end='') 7 | result = 0 8 | for n in range(count): 9 | result += n + 1 10 | time.sleep(1) 11 | print(f"{name} - end with {result}") 12 | 13 | 14 | def start_process_1(): 15 | process = multiprocessing.Process(target=task, args=["A", 100]) 16 | 17 | process.start() 18 | 19 | process.join() 20 | 21 | print("Main process over") 22 | 23 | 24 | def start_process_2(): 25 | args_list = [("A", 100), ("B", 99), ("C", 98)] 26 | processes = [multiprocessing.Process(target=task, args=[name, count]) for name, count in args_list] 27 | 28 | for p in processes: 29 | p.start() 30 | 31 | for p in processes: 32 | p.join() 33 | 34 | 35 | if __name__ == "__main__": 36 | start_process_2() 37 | -------------------------------------------------------------------------------- /nonlocal/__main__.py: -------------------------------------------------------------------------------- 1 | message = "module" 2 | 3 | 4 | def outer(): 5 | message = "outer" 6 | 7 | def inner(): 8 | nonlocal message 9 | 10 | message = "inner" 11 | print(message) 12 | 13 | inner() 14 | print(message) 15 | 16 | 17 | outer() 18 | 19 | print(message) 20 | -------------------------------------------------------------------------------- /processpool/__main__.py: -------------------------------------------------------------------------------- 1 | import os.path 2 | import time 3 | from concurrent.futures import ProcessPoolExecutor 4 | from urllib.request import urlopen, Request 5 | 6 | 7 | def download_img(url: str): 8 | site_url = Request(url, headers={"User-Agent": "Mozilla/5.0"}) 9 | with urlopen(site_url) as web_file: 10 | img_data = web_file.read() 11 | 12 | if not img_data: 13 | raise Exception(f"Error: cannot load the image from {url}") 14 | 15 | file_name = os.path.basename(url) 16 | with open(file_name, 'wb') as file: 17 | file.write(img_data) 18 | 19 | return f"Download image successfully, {url}" 20 | 21 | 22 | def main(): 23 | with ProcessPoolExecutor() as executor: 24 | urls = [ 25 | "https://cdn.pixabay.com/photo/2021/09/28/13/14/cat-6664412_1280.jpg", 26 | "https://cdn.pixabay.com/photo/2022/11/10/00/38/creative-7581718_640.jpg", 27 | "https://cdn.pixabay.com/photo/2022/11/19/11/53/rose-7601873_640.jpg", 28 | "https://cdn.pixabay.com/photo/2022/10/18/12/05/clouds-7530090_640.jpg" 29 | ] 30 | 31 | results = executor.map(download_img, urls) 32 | 33 | for res in results: 34 | print(res) 35 | 36 | 37 | if __name__ == "__main__": 38 | main() 39 | 40 | -------------------------------------------------------------------------------- /regex/__main__.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def test_search(): 5 | pattern = r"\d{2}" 6 | source = "I'm 80 years old." 7 | 8 | result = re.search(pattern, source) 9 | print(result) 10 | 11 | 12 | def test_match(): 13 | pattern = r"\d{2}" 14 | source = "80 years old." 15 | 16 | result = re.match(pattern, source) 17 | print(result) 18 | 19 | 20 | def test_fullmatch(): 21 | pattern = r"\d{2}" 22 | source = "809" 23 | 24 | result = re.fullmatch(pattern, source) 25 | print(result) 26 | 27 | 28 | def test_findall(): 29 | pattern = r"\d{2}" 30 | source = "8 09 aaa 89 laskdjf" 31 | 32 | result = re.findall(pattern, source) 33 | print(result) 34 | 35 | 36 | def test_finditer(): 37 | pattern = r"\d{2}" 38 | source = "8 09 aaa 89 laskdjf" 39 | 40 | it = re.finditer(pattern, source) 41 | for rs in it: 42 | print(rs) 43 | 44 | 45 | def test_compile(): 46 | pattern_str = r"\d{2}" 47 | pattern = re.compile(pattern_str) 48 | print(pattern.fullmatch("99")) 49 | 50 | 51 | test_compile() 52 | -------------------------------------------------------------------------------- /singleton/__main__.py: -------------------------------------------------------------------------------- 1 | def singleton(cls): 2 | _instance = {} 3 | 4 | def inner(*args, **kwargs): 5 | if cls in _instance: 6 | return _instance[cls] 7 | 8 | obj = cls(*args, **kwargs) 9 | _instance[cls] = obj 10 | 11 | return obj 12 | 13 | return inner 14 | 15 | 16 | class SingletonMeta(type): 17 | def __call__(cls, *args, **kwargs): 18 | if hasattr(cls, '_instance'): 19 | return getattr(cls, '_instance') 20 | 21 | obj = super().__call__(*args, **kwargs) 22 | setattr(cls, '_instance', obj) 23 | 24 | return obj 25 | 26 | 27 | # @singleton 28 | class Person(metaclass=SingletonMeta): 29 | pass 30 | 31 | 32 | p_1 = Person() 33 | p_2 = Person() 34 | 35 | print(p_1 is p_2) 36 | -------------------------------------------------------------------------------- /threadlock/__main__.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Lock, Condition 2 | 3 | 4 | task_lock = Lock() 5 | 6 | 7 | def task(name: str): 8 | global task_lock 9 | for n in range(2): 10 | task_lock.acquire() 11 | print(f"{name} - round {n} - step 1\n", end='') 12 | print(f"{name} - round {n} - step 2\n", end='') 13 | print(f"{name} - round {n} - step 3\n", end='') 14 | task_lock.release() 15 | 16 | 17 | t1 = Thread(target=task, args=("A",)) 18 | t2 = Thread(target=task, args=("B",)) 19 | t3 = Thread(target=task, args=("C",)) 20 | 21 | t1.start() 22 | t2.start() 23 | t3.start() 24 | 25 | 26 | class SafeQueue: 27 | def __init__(self, size: int): 28 | self.__item_list = list() 29 | self.size = size 30 | self.__item_lock = Condition() 31 | 32 | def put(self, item): 33 | with self.__item_lock: 34 | while len(self.__item_list) >= self.size: 35 | self.__item_lock.wait() 36 | 37 | self.__item_list.insert(0, item) 38 | self.__item_lock.notify_all() 39 | 40 | def get(self): 41 | with self.__item_lock: 42 | while len(self.__item_list) == 0: 43 | self.__item_lock.wait() 44 | 45 | result = self.__item_list.pop() 46 | self.__item_lock.notify_all() 47 | 48 | return result 49 | 50 | 51 | class MsgProducer(Thread): 52 | def __init__(self, name: str, count: int, queue: SafeQueue): 53 | super().__init__() 54 | 55 | self.setName(name) 56 | self.count = count 57 | self.queue = queue 58 | 59 | def run(self) -> None: 60 | for n in range(self.count): 61 | msg = f"{self.getName()} - {n}" 62 | self.queue.put(msg) 63 | 64 | 65 | class MsgConsumer(Thread): 66 | def __init__(self, name: str, queue: SafeQueue): 67 | super().__init__() 68 | 69 | self.setName(name) 70 | self.queue = queue 71 | self.setDaemon(True) 72 | 73 | def run(self) -> None: 74 | while True: 75 | msg = self.queue.get() 76 | print(f"{self.getName()} - {msg}\n", end='') 77 | 78 | 79 | queue = SafeQueue(3) 80 | threads = list() 81 | threads.append(MsgProducer("PA", 10, queue)) 82 | threads.append(MsgProducer("PB", 10, queue)) 83 | threads.append(MsgProducer("PC", 10, queue)) 84 | 85 | threads.append(MsgConsumer("CA", queue)) 86 | threads.append(MsgConsumer("CB", queue)) 87 | 88 | for t in threads: 89 | t.start() 90 | -------------------------------------------------------------------------------- /threadpool/__main__.py: -------------------------------------------------------------------------------- 1 | import os.path 2 | import time 3 | from concurrent.futures import ThreadPoolExecutor 4 | from urllib.request import urlopen, Request 5 | 6 | 7 | def task(name: str): 8 | print(f"{name} - step 1\n", end='') 9 | time.sleep(1) 10 | print(f"{name} - step 2\n", end='') 11 | 12 | return f"{name} complete" 13 | 14 | # 15 | # with ThreadPoolExecutor() as executor: 16 | # result_1 = executor.submit(task, 'A') 17 | # result_2 = executor.submit(task, 'B') 18 | # 19 | # print(result_1.result()) 20 | # print(result_2.result()) 21 | # 22 | # with ThreadPoolExecutor() as executor: 23 | # results = executor.map(task, ['C', 'D']) 24 | # 25 | # for r in results: 26 | # print(r) 27 | 28 | 29 | def download_img(url: str): 30 | site_url = Request(url, headers={"User-Agent": "Mozilla/5.0"}) 31 | with urlopen(site_url) as web_file: 32 | img_data = web_file.read() 33 | 34 | if not img_data: 35 | raise Exception(f"Error: cannot load the image from {url}") 36 | 37 | file_name = os.path.basename(url) 38 | with open(file_name, 'wb') as file: 39 | file.write(img_data) 40 | 41 | return f"Download image successfully, {url}" 42 | 43 | 44 | with ThreadPoolExecutor() as executor: 45 | urls = [ 46 | "https://cdn.pixabay.com/photo/2021/09/28/13/14/cat-6664412_1280.jpg", 47 | "https://cdn.pixabay.com/photo/2022/11/10/00/38/creative-7581718_640.jpg", 48 | "https://cdn.pixabay.com/photo/2022/11/19/11/53/rose-7601873_640.jpg", 49 | "https://cdn.pixabay.com/photo/2022/10/18/12/05/clouds-7530090_640.jpg" 50 | ] 51 | 52 | results = executor.map(download_img, urls) 53 | 54 | for res in results: 55 | print(res) 56 | -------------------------------------------------------------------------------- /threads/__main__.py: -------------------------------------------------------------------------------- 1 | from threading import Thread 2 | 3 | 4 | def task(count: int): 5 | for n in range(count): 6 | print(n) 7 | 8 | 9 | thread1 = Thread(target=task, args=(10,)) 10 | thread2 = Thread(target=task, args=(20,)) 11 | 12 | thread1.start() 13 | thread2.start() 14 | 15 | thread1.join() 16 | thread2.join() 17 | 18 | print("Main threads is end") 19 | -------------------------------------------------------------------------------- /typeclass/__main__.py: -------------------------------------------------------------------------------- 1 | class Student: 2 | def greeting(self): 3 | print("Hello student") 4 | 5 | 6 | print(type(Student)) 7 | print(isinstance(Student, type)) 8 | 9 | 10 | class_body = """ 11 | def greeting(self): 12 | print('Hello customer') 13 | 14 | def jump(self): 15 | print('jump') 16 | """ 17 | class_dict = {} 18 | exec(class_body, globals(), class_dict) 19 | 20 | Customer = type("Customer", (object,), class_dict) 21 | 22 | c = Customer() 23 | c.greeting() 24 | c.jump() 25 | -------------------------------------------------------------------------------- /variablescope/__main__.py: -------------------------------------------------------------------------------- 1 | count = 10 2 | 3 | print(count) 4 | 5 | 6 | def greeting(flag: bool): 7 | global count 8 | if flag: 9 | count = 20 10 | 11 | print(count) 12 | 13 | 14 | greeting(True) 15 | 16 | print(count) 17 | 18 | -------------------------------------------------------------------------------- /yield_from/__main__.py: -------------------------------------------------------------------------------- 1 | def magic_number(exponent: int): 2 | for n in range(3): 3 | yield (n + 1) ** exponent 4 | 5 | 6 | def magic_data(): 7 | yield from magic_number(2) 8 | yield from magic_number(3) 9 | 10 | 11 | # for n in magic_data(): 12 | # print(n) 13 | 14 | 15 | def magic_two(): 16 | exponent = yield 'Please give an exponent based on two' 17 | 18 | while True: 19 | exponent = yield 2 ** exponent 20 | 21 | if exponent is None: 22 | break 23 | 24 | 25 | # m = magic_two() 26 | # print(next(m)) 27 | # 28 | # print(m.send(2)) 29 | # 30 | # print(m.send(3)) 31 | # 32 | # try: 33 | # m.send(None) 34 | # except StopIteration: 35 | # pass 36 | 37 | 38 | def magic_three(): 39 | exponent = yield 'Please give an exponent based on three' 40 | 41 | while True: 42 | exponent = yield 3 ** exponent 43 | 44 | if exponent is None: 45 | break 46 | 47 | 48 | def magic_switch(): 49 | option = yield 'Please choose, 1 - two, 2 - three' 50 | 51 | while True: 52 | if option == 1: 53 | yield from magic_two() 54 | elif option == 2: 55 | yield from magic_three() 56 | else: 57 | break 58 | 59 | 60 | mm = magic_switch() 61 | print(next(mm)) 62 | print(mm.send(2)) 63 | print(mm.send(2)) 64 | print(mm.send(3)) 65 | try: 66 | mm.send(None) 67 | except StopIteration: 68 | pass 69 | 70 | --------------------------------------------------------------------------------