Built-in variable to get current function

2024/11/18 19:53:02

I have a lot of functions like the following, which recursively call themselves to get one or many returns depending on the type of the argument:

def get_data_sensor(self, sensorname):if isinstance(sensorname, list):return [get_data_sensor(self, sensor) for sensor in sensorname]return get_data(os.path.join(self.get_info("path"), "{0}.npy".format(sensorname)))

I would like to call my function recursively without having to know my current function name, I don't want to have my function name twice in the code to limit copy-paste error.

Determine function name from within that function (without using traceback) shows how to get the actual function name, but I need the function itself to call it.

Answer

You can abstract that logic outside the function entirely by using a decorator (see this thorough answer if you're unfamiliar with decorators):

from functools import wrapsdef autolist(func):@wraps(func)def wrapper(args):if isinstance(args, list):return [func(arg) for arg in args]return func(args)return wrapper

This decorator can be applied to any function requiring the pattern, which now only needs to implement the scalar case:

>>> @autolist
... def square(x):
...     return x ** 2
...
>>> square(1)
1
>>> square([1, 2, 3])
[1, 4, 9]

If you're applying it to a method, as self implies, you'll also need to take that argument into account in the wrapper. For example, if the relevant argument is always the last one you could do:

def autolist(func):@wraps(func)def wrapper(*args):*args, last_arg = argsif isinstance(last_arg, list):return [func(*args, arg) for arg in last_arg]return func(*args, last_arg)return wrapper

This would work on methods, too:

>>> class Squarer:
...     @autolist
...     def square(self, x):
...             return x ** 2
...
>>> Squarer().square(1)
1
>>> Squarer().square([1, 2, 3])
[1, 4, 9]
https://en.xdnf.cn/q/119942.html

Related Q&A

Python run from subdirectory

I have the following file hierarchy structure:main.py Main/A/a.pyb.pyc.pyB/a.pyb.pyc.pyC/a.pyb.pyc.pyFrom main.py I would like to execute any of the scripts in any of the subfolders. The user will pass…

How to create duplicate for each value in a python list given the number of dups I want?

I have this list: a=[7086, 4914, 1321, 1887, 7060]. Now, I want to create duplicate of each value n-times. Such as: n=2a=[7086,7086,4914,4914,1321,1321,7060,7060]How would I do this best? I tried a lo…

How do I generate random float and round it to 1 decimal place

How would I go about generating a random float and then rounding that float to the nearest decimal point in Python 3.4?

Error extracting text from website: AttributeError NoneType object has no attribute get_text

I am scraping this website and get "title" and "category" as text using .get_text().strip().I have a problem using the same approach for extracting the "author" as text.d…

Fastest way to extract tar files using Python

I have to extract hundreds of tar.bz files each with size of 5GB. So tried the following code:import tarfile from multiprocessing import Poolfiles = glob.glob(D:\\*.tar.bz) ##All my files are in D for …

Python - Split a string but keep contiguous uppercase letters [duplicate]

This question already has answers here:Splitting on group of capital letters in python(3 answers)Closed 3 years ago.I would like to split strings to separate words by capital letters, but if it contain…

Python: Find a Sentence between some website-tags using regex

I want to find a sentence between the ...class="question-hyperlink"> tags. With this code:import urllib2 import reresponse = urllib2.urlopen(https://stackoverflow.com/questions/tagged/pyth…

How to download all the href (pdf) inside a class with python beautiful soup?

I have around 900 pages and each page contains 10 buttons (each button has pdf). I want to download all the pdfs - the program should browse to all the pages and download the pdfs one by one. Code only…

Reducing the complexity/computation time for a basic graph formula [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 4 years ago.Improve…

Find All Possible Fixed Size String Python

Problem: I want to generate all possible combination from 36 characters that consist of alphabet and numbers in a fixed length string. Assume that the term "fixed length" is the upper bound f…