All Questions
Tagged with meta-programming python
71 questions
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 ...
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 ...
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 ...
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, ...
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 ...
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 ...
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 ...
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 ...
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 ...
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:
...
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":
...
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.
...
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 ...
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 ...
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 ...
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 ...
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.
...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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:
...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 (...
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 ...
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.
...
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. ...
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 :
...
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 ...
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:
...
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__, ...
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:
...
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, ...
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 ...
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 ...
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?
...
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
...