python
-
Tipspython/응용 2023. 8. 20. 18:58
https://betterprogramming.pub/87-lesser-known-python-features-635180720a29 87 Lesser-known Python Features This post is for people who use Python daily, but have never actually sat down and read through all the documentation. betterprogramming.pub str.endswith(), isinstance() take a tuple if filename.endswith((".csv", ".xls", ".xlsx")) # Do something spreadsheety assert isinstance(7, (float, int..
-
Generators in pythonpython/응용 2023. 8. 20. 17:47
https://medium.com/python-in-plain-english/10-surprising-ways-to-use-generators-in-python-426a38a0d5eb Generating Infinite Sequences def natural_number(): n = 1 while True: yield n n += 1 for num in natural_number(): print(num) if num >= 10: break nat = natural_number() for _ in range(10): print(next(nat)) Generating Large Fibonacci Sequences def fibonacci(): a, b = 0, 1 while True: yield a a, b..
-
Pydantic 으로 dataclass 대체하기python/응용 2023. 7. 29. 22:13
https://wefree.tistory.com/280 의 dataclass 기능을 pydantic 2.x 로 대체해 보자 import random import string from typing import Any from pydantic import BaseModel, Field, ConfigDict def generate_id() -> str: return ''.join(random.choices(string.ascii_lowercase, k=12)) class Person(BaseModel): name: str phone_numbers: list[str] = [] id: str = Field(default_factory=generate_id) @property def phone_numbers_len..
-
functools.cachepython/응용 2023. 7. 13. 19:05
코드 import contextlib import functools import time @contextlib.contextmanager def timer(): start = time.time() yield end = time.time() elapsed = round(end - start, 3) print(f"{elapsed=}s") @functools.cache def sleep(n): time.sleep(n) with timer(): sleep(2) with timer(): sleep(2) 결과 elapsed=2.004s elapsed=0.0s 참고 https://pub.towardsai.net/20-underdog-python-built-in-libraries-that-deserve-much-mor..
-
pydantic: dictionary 를 object 로 변환 / json 출력python/응용 2023. 7. 10. 12:02
코드 import pydantic class Person(pydantic.BaseModel): name: str age: int data = [ { "name": "A", "age": 1 }, { "name": "B", "age": 2 } ] people = [Person(**x) for x in data] print(people) print(people[0].json()) 결과 [Person(name='A', age=1), Person(name='B', age=2)] {"name": "A", "age": 1}
-
dataclass: sortpython/응용 2023. 7. 10. 11:40
코드 from dataclasses import dataclass, field @dataclass(order=True) class Person: sort_index: int = field(init=False, repr=False) name: str age: int def __post_init__(self): self.sort_index = self.age person1 = Person("Garalt", 30) person2 = Person("Yennefer", 25) print(person1 > person2) print(person1) 결과 True Person(name='Garalt', age=30) 주의 sort_index 필드가 가장 맨 처음으로 와야 한다. (dataclass 는 기본적으로 필드..
-
dataclass: mutable default valuespython/응용 2023. 7. 9. 17:19
아래 코드에서 phone_numbers 는 모든 객체들이 공유되어, 의도하지 않는 결과가 발생시킬 수 있다. 이를 막기 위해 파이썬에서는 'ValueError: mutable default for field phone_numbers is not allowed: use default_factory' 에러가 나도록 설계된 것 같다. https://docs.python.org/3/library/dataclasses.html#mutable-default-values 참고 from dataclasses import dataclass @dataclass class Person: name: str phone_numbers: list[str] = [] 에러 메시지에 나온 것 처럼 'default_factory' 를 사..
-
functools.partial() 활용python/응용 2023. 7. 7. 21:37
강의: https://youtu.be/ph2HjBQuI8Y 코드: https://github.com/ArjanCodes/2022-functions/tree/main 좀 더 간단한 예제 코드를 만들어 봄 import functools from typing import Callable def circle_area(pi: float, radius: float) -> float: return pi * radius * radius CircleAreaFunction = Callable[[float], float] def is_big_circle(radius: float, f: CircleAreaFunction) -> bool: area: float = f(radius) if area >= 310: return Tr..