Skip to main content

All Questions

Filter by
Sorted by
Tagged with
16 votes
1 answer
25k views

Decorator to measure execution time of a function

This decorator adds the elapsed time to a function's attributes when applied. My concerns: Is the code pythonic? Could this code be useful? Should I just use the ...
Ricky Wilson's user avatar
  • 1,695
12 votes
2 answers
2k views

Memoizing decorator that can retry

I have some tasks that I'd like to memoize because they connect to a rather slow network and have to wait for the data. Unfortunately this network can be a little finnicky and we get occasional ...
Dan Oberlam's user avatar
  • 7,854
12 votes
1 answer
550 views

Using decorated methods in a subclass of deque to dump its state to a JSON file

I am sub-classing an object in python and I need to overload a bunch of the methods with very similar logic, essentially a call to super() and then some additional operations. I want to avoid ...
Alex's user avatar
  • 223
12 votes
1 answer
189 views

Generic framework to handle parameterized commands

I asked this question a while ago, and this was one of the comments: There (mostly) seems to be a one-to-one mapping of a lot of your functions to IRC command verbs. For example, ...
Dan Oberlam's user avatar
  • 7,854
11 votes
1 answer
4k views

Try-except decorator for classmethods

This question is related to the Cactus Text Game Engine. For easy error handling in Cactus, we've put together this small decorator. Essentially, the decorator wraps any class method in a ...
Ethan Bierlein's user avatar
11 votes
3 answers
1k views

Simple generic auto __repr__

Preface At some point I was tired of writing & supporting __repr__ methods, so I've decided to write it once and reuse everywhere in my classes. Since I'm ...
Azat Ibrakov's user avatar
11 votes
2 answers
2k views

Improving the Flask cache decorator

In my rumblings developing flask applications I found the caching decorator. The decorator is a short and well-written piece of code, but I feel like it misses the few points bellow: It only caches ...
user avatar
10 votes
2 answers
4k views

Mutable Named Tuple - or - Slotted Data Structure

A question I answered on Stack Overflow asked for a mutable named tuple. The naive answer would probably tell them they just want to define a custom object. However, named tuples take up a lot ...
Aaron Hall's user avatar
  • 1,568
9 votes
1 answer
768 views

Change arbitrary arguments of function based on their names with a decorator

I ran across an issue that proved to be more complicated than I thought: Changing an arbitrary argument of a function purely based upon its name in Python - possibly via a decorator. I tried to ...
s-m-e's user avatar
  • 273
9 votes
2 answers
2k views

Python Export Decorator

In Python, we use __all__ to explicitly denote the public API of a module or package. That looks like this: ...
Aaron Hall's user avatar
  • 1,568
9 votes
1 answer
832 views

Multiple dispatch decorator classes in Python

This is based on my first review and the suggested points in "Multiple dispatch decorator in Python": ...
Joschua's user avatar
  • 454
8 votes
2 answers
902 views

Strict types decorator (works only with Python 3.5)

I wrote a decorator which makes Python 3.5 raise exceptions if the arguments that are passed to a type-hinted function are of the wrong type. ...
Ilya Peterov's user avatar
7 votes
2 answers
155 views

Python class compressor

After watching this presentation, I decided that it would be a good project for me to undergo to practice my python skills. A summary of the presentation: Jack ...
Linny's user avatar
  • 10.4k
7 votes
1 answer
295 views

Using Python decorators to do Hoare Logic

I'm relatively new to Python from a strong Java background. I am trying to create a base class to do Hoare Logic. Function decorators seem to be the way to go with this. I've produced the following ...
Martin of Hessle's user avatar
7 votes
1 answer
1k views

Decorator to return default argument values

I'm using Python 3.6. This code, used as a decorator to a python function, will cause the function to return a dict of POSITION_OR_KEYWORD arguments. I used this ...
James Schinner's user avatar
7 votes
1 answer
96 views

Basic profiler - Python

I have created a simple profiler in Python, but I feel like there are better ways to do some things. Terminology: Section - a block of code to profile Label - A name for a section to be used as a ...
internet_user's user avatar
7 votes
1 answer
444 views

Game loop decorator for Pygame

I've built a simple decorator that wraps a function in a general Pygame game loop. It also allows for the programmer to set the tick rate. ...
Ethan Bierlein's user avatar
7 votes
1 answer
342 views

Monkeypatching __builtin__ in tests for mocking

I'm testing a little magic behaviour of my script that automatically reads from ~/.ghtoken to do automagic authentication on GitHub API requests. I want to test ...
Eddie Antonio Santos's user avatar
6 votes
2 answers
478 views

LazyEnum with validation

Motivation In the standard Python library enum, a subclass of Enum would create all its members upon class creation. This can ...
user141240's user avatar
6 votes
3 answers
583 views

Memoizing decorator with retries, part 2

A while ago I asked this question Memoizing decorator that can retry and then promptly forgot about it. I more recently saw Python decorator for retrying w/exponential backoff and wanted to add ...
Dan Oberlam's user avatar
  • 7,854
6 votes
2 answers
459 views

Class Decorator for Verifying Method-Level Permissions

After writing far too many if has_permission(user): statements at the head of my methods, I figured I would try my hand at writing a generic enough decorator to do ...
Christopher Sheaf's user avatar
6 votes
2 answers
7k views

Custom array indexing

Note that this code is not going to be used for anything, it's more of a thought experiment. I've been seeing a lot of NumPy code lately and noticed that they use a custom indexing process, presumably ...
Jared Goguen's user avatar
6 votes
1 answer
2k views

Hooking with Python3 Decorators

I wrote this prototype after reading the Wikipedia article on hooking. I didn't bother to read any of the code examples listed there because, well, I just didn't. I don't have a good excuse. The ...
user avatar
5 votes
2 answers
11k views

Python decorator for retrying w/exponential backoff

This is my first decorator in Python! I found some of it on the internet but have tweaked it to our needs. Here is the couple concerns of mine: Multiple python version compatibility Is grabbing the ...
Jared Mackey's user avatar
5 votes
1 answer
740 views

Descriptor class with advanced (inspect/metaclass) functionality

Having answered this question over on Programmers.SE, I found myself wondering how much effort it would be to write a descriptor that can automatically figure out what the 'destination' attribute ...
jonrsharpe's user avatar
  • 13.9k
5 votes
0 answers
891 views

Writing a metaclass to ensure a class is thread-safe

Python allows the creation of classes to be modified via metaclasses. They can perform all sorts of operations that might appear to be magical to languages that do not have the capability. The goal of ...
Noctis Skytower's user avatar
5 votes
0 answers
715 views

Implement OO interfaces in Python

Edit: Whoops! I just remembered there's already an long-lived package for this, zope.interface. I'd like a review all the same. This is a proof-of-concept ...
shadowtalker's user avatar
4 votes
4 answers
3k views

Python Decorator - inspecting function argument values

Some of my functions use a "fail_silently" flag. It is used in the following way: ...
user1639926's user avatar
4 votes
1 answer
819 views

Universal memoization decorator

I've just written a simple caching / memoization python decorator. It's purpose is to cache what the function returns for all the arguments combinations it's been ever invoked with. So, if, say, we ...
rroszkowiak's user avatar
4 votes
1 answer
14k views

Python decorator to support static properties

Classes in Python do not have native support for static properties. A meta-class can rather easily add this support as shown below. Are there any problems programmers might experience if they use this ...
Noctis Skytower's user avatar
4 votes
1 answer
4k views

Class decorator in Python to set variables for the constructor

I personally don't like the boilerplate of most __init__ methods: self.a = a self.b = b ... So I thought this would be a nice ...
magu_'s user avatar
  • 938
4 votes
1 answer
140 views

A self contained parser generator implementation

This is a recreational project, I was trying to make a parser generator with a grammar inspired from: https://docs.python.org/3/reference/grammar.html Unfortunately, understanding that specific ...
Jeacom's user avatar
  • 125
4 votes
1 answer
2k views

login_required decorator in Flask

I have 2 Flask apps (different projects) that work together . One implements some API which uses tokens for auth. The second one consumes the API and makes a web interface for it. Now I have a login ...
utkbansal's user avatar
  • 223
4 votes
1 answer
3k views

Dictionary with restricted keys

I'm currently building some software that works with systemd unit files, and I've been trying to improve how we construct the unit files. This is all running in Python 3.4 This first block is the ...
Techdragon's user avatar
4 votes
1 answer
68 views

Decorator to add key parameter support to an existing sort function

Preface sorted built-in function has key keyword-only parameter. Most of the custom implementations like the following for ...
Azat Ibrakov's user avatar
4 votes
1 answer
820 views

Meta-class to allow inspection of all __slots__of a class

If classes provide __slots__ and at the same time inherit from another class also providing __slots__, there is no ...
SmCaterpillar's user avatar
4 votes
0 answers
102 views

Inherit docstrings from specified parent

I was recently working on some python where I was working with multiple inheritance and mixins and stuff like that, and I wanted to inherit docstrings for specific functions, from specific parents (...
Andrew's user avatar
  • 61
4 votes
0 answers
317 views

Python breakpoints in Vim (Vimscript)

I recently decided that putting strategically placed print statements scattered about my python programs to debug was getting to be a little messy. I had thought ...
Jebby's user avatar
  • 261
3 votes
2 answers
6k views

Failing fast by raising an exception with a custom message

This is a script that utilizes lazy exception throwing. What I do is decorate a function that might throw an exception to throw an exception with a formatted string. ...
JaDogg's user avatar
  • 4,531
3 votes
1 answer
595 views

Decorate instance method with (arbitrary) meta data in python

Requirements What I need: attach meta information to methods, such that it is 'easy' to retrieve all such methods for a given class instance methods can still be called 'in a normal way', e.g. ...
Michael Hoff's user avatar
3 votes
1 answer
1k views

Python simple type checking decorator

I'd like to know your opinions on this minimal type-checking decorator (with @ annotations) to make type checking of a method while debugging like : ...
user8426627's user avatar
3 votes
1 answer
2k views

Transforming stored procedures using Python regular expressions

I have to add some extra logic to about 80 similar stored procedures on my DWH server. I thought that it would take pretty much the same time if I do it with Python and lots of googling (I have no ...
Raphael Müllner's user avatar
3 votes
1 answer
121 views

clean approach to decorator that takes optional keyword arguments [closed]

I write decorators a lot in my work. Sometimes you need to write "decorator that takes arguments", it usually turns out to be something like this: ...
rabbit.aaron's user avatar
3 votes
1 answer
950 views

Lombokython - Automatic __eq__, __hash__, __repr__

I recently decided to code some in Python after coding in Java using lombok for quite some time. However, I got bit real hard when I forgot to implement __eq__, ...
Justin's user avatar
  • 3,295
3 votes
1 answer
82 views

user_interface module

As writing code to handle error-checked input or to present functions to execute to the user is boring and error-prone, I wrote a module to automate these tasks: ...
Caridorc's user avatar
  • 27.6k
3 votes
2 answers
240 views

Synchronous and asynchronous motor movement

I am working on an API that is mostly intended to be used interactively/little scripts. There are some classes with methods that could act slightly differently depending on the intention of the user, ...
agomcas's user avatar
  • 143
3 votes
1 answer
666 views

Function overloading in Python

Motivation As an exercise, I wanted to try implementing function overloading in Python 3, i.e. to implement a way of defining multiple functions with the same name and then calling the appropriate ...
igal's user avatar
  • 381
3 votes
1 answer
359 views

Streamlining repetitive class definitions in python with a class_factory() function

I forked this repo to be more concise. The code is here. I'll paste it below since that seems to be the style. I removed the class definitions at the bottom that I didn't change -- the edit I'm ...
Patrick Collins's user avatar
3 votes
1 answer
84 views

caching decorator

I came up with a caching decorator for pure functions. Is it ok? Could it be better/simpler/faster? ...
Eugene's user avatar
  • 323
3 votes
1 answer
453 views

General way to add persistence to a class in Python

The idea here is to write a function that gives you back a persistent version of a class that you supply. So you if you run ...
kuzzooroo's user avatar
  • 369