Category : python-decorators

Consider a trivial example: class C: @staticmethod def my_static_method(): print("static") def my_instance_method(self): print("self") When I call C().my_static_method(), python doesn’t pass the instance of C into my_static_method, and the descriptor that my_static_method references doesn’t expect an instance of C, either. This makes sense. But then when I call C().my_instance_method(), how does python know to pass the ..

Read more

I’ve seen code such as @login_required() def user_profile(request): # do stuff here I’ve also seen some code written as @login_required def user_profile(request): # do stuff here Note the missing () in the second example. On testing, both of them work the same. Is there any difference between the 2 approaches? Source: Python..

Read more

I’m looking for a means to trace all calls on an instance of a class, including calls to dunder methods like __iter__, __getattribute__ etc. I’ve tried using sys.setprofile, the autologging package, but failed : it doesn’t seem to be able to trace calls to dundermethods, or attributes etc. My usecase is the following. Python’s duck ..

Read more

I have a codebase with a lot of repeated logic – mainly around input validation. Eg. def get_temperature(country:str, date:str|None=None)->float: date = pd.to_datetime(date).date() if date is not None else datetime.now().date() country = lookup_country_isocode(country) … def get_sunset_time(country:str, date:str|None=None)->float: date = pd.to_datetime(date).date() if date is not None else datetime.now().date() country = lookup_country_isocode(country) … def get_sunrise_time(country:str, date:str|None=None)->float: date = ..

Read more

I have the following dataclass: @dataclass(frozen=True) class Info: client_id: str purchase_id: str Both these ids are supposed to be UUID’s. I have a method that can check if the arg is UUID: from uuid import UUID def check_uuid(arg): try: UUID(arg) except ValueError: raise argparse.ArgumentTypeError(f"'{arg}’ is not a valid UUID") return arg I want to define ..

Read more

I’m trying to make class that can clean text. The class has several methods, like converting text to lower case, spell checking the text, lemmatizing the text, removing special characters etc. Finally I have a method (cleaned_text) that calls all the above methods in order and returns the final cleaned text. Here is the code. ..

Read more