[Python] Make sure the received function is a user-defined function

These tips can be used when you want to check "Is the given function really a user-implemented function?" When creating a library in Python.

First determine if it is a function

Needless to say this.

import inspect
inspect.isfunction(func)

Determine if it is a built-in function or frozen function

In Python, you can use the built-in functions written in C language and the frozen functions built into the Python processing system in the form of bytecode among the standard libraries written in Python. For example, builtins.sorted () is a built-in function and zipimport.zipimporter () is a frozen function.

How to use sys.modules

This is relatively straightforward, but it looks for a module object with func defined in sys.modules. If it doesn't have the __file__ attribute, it's a built-in function or a frozen function. (Except for built-in modules and frozen modules, Python always has a one-to-one correspondence with files.)

modname = func.__module__
mod = sys.modules[modname]
fname = getattr(mod, '__file__', None)
return fname != None

How to use the code object

There are the following methods as other methods. I think this is more concise.

co = getattr(func, '__code__', None)
return co != None

Determine if it is a user-created function

I think there are several ways, but here if you get the path of the file where the function is defined and it is located under the __main__ module path (working directory for STDIN), then in the existing library It is determined that the file is created by the user. Note that this decision may not work for package managers (such as pyflow) that put the library cache under the working directory. Also, it may not work if you are doing ʻimport while changing the working directory using ʻos.chdir etc. (I don't know if there is such a program)

filename = path.abspath(co.co_filename)
return filename.startswith(path.join(get_maindir(), ''))

def get_maindir():
    mm = sys.modules['__main__']
    fname = getattr(mm, '__file__', None)
    if fname == None:
        # STDIN
        return os.getcwd()
    else:
        return path.dirname(path.abspath(mm.__file__))

All source code

import sys
import os
import inspect
from os import path
def is_userfunc_b(func):
    if not inspect.isfunction(func):
        return False
    modname = func.__module__
    mod = sys.modules[modname]
    fname = getattr(mod, '__file__', None)
    if fname == None:
        return false
    fname = path.abspath(fname)
    return fname.startswith(path.join(get_maindir(), ''))
    
def is_userfunc(func):
    if not inspect.isfunction(func):
        return False
    co = getattr(func, '__code__', None)
    if co == None:
        return False
    # Check that the file is placed under main module
    filename = path.abspath(co.co_filename)
    return filename.startswith(path.join(get_maindir(), ''))

def get_maindir():
    mm = sys.modules['__main__']
    fname = getattr(mm, '__file__', None)
    if fname == None:
        # STDIN
        return os.getcwd()
    else:
        return path.dirname(path.abspath(mm.__file__))

Recommended Posts

[Python] Make sure the received function is a user-defined function
[Python] Make the function a lambda function
[python] [meta] Is the type of python a type?
Get the caller of a function in Python
Make a copy of the list in Python
Make a function decorator
[Python] Smasher tried to make the video loading process a function using a generator
Check if the string is a number in python
[Practice] Make a Watson app with Python! # 2 [Translation function]
Make a breakpoint on the c layer with python
What is God? Make a simple chatbot with python
"Cython" tutorial to make Python explosive: Handling when a function on the C ++ side is passed by reference.
What does the last () in a function mean in Python?
Create a function in Python
What is the activation function?
About the enumerate function (python)
Python list is not a list
Make a bookmarklet in Python
Make a fortune with Python
What is a callback function?
What is the Callback function?
The image is a slug
What is a python map?
Associate Python Enum with a function and make it Callable
Check the argument type annotation when executing a function in Python and make an error
[Python] Make the format function simpler (What is f-string? Explain the difference from the format function with an example)
Call a Python function from p5.js.
Play a sound in Python assuming that the keyboard is a piano keyboard
To make sure that the specified key is in the specified bucket in Boto 3
"Cython" tutorial to make Python explosive: When a function on the C ++ side has an overload.
[Introduction to Python] How to split a character string with the split function
Let's make a GUI with python.
[Python] What is @? (About the decorator)
[Python] Execution time when a function is entered in a dictionary value
Delete a particular character in Python if it is the last
How to make a recursive function
[python] What is the sorted key?
python / Make a dict from a list.
A function that measures the processing time of a method in python
[Python3] Define a decorator to measure the execution time of a function
I made a function to check if the webhook is received in Lambda for the time being
What is the python underscore (_) for?
Let's make a graph with python! !!
[Python] A simple function to find the center coordinates of a circle
Finally ... Make a radio control using python on Raspberry Pi 3! (The motor moves while the button is pressed)
[Python] What is a formal argument? How to set the initial value
What is the XX file at the root of a popular Python project?
[Introduction to Python] What is the difference between a list and a tuple?
[Python] Explains how to use the range function with a concrete example
The eval () function that calculates a string as an expression in python
A shell script to make sure you don't forget the pipenv shell again
[Introduction to Python] How to write a character string with the format function
Python: I want to measure the processing time of a function neatly
What is the fastest way to create a reverse dictionary in python?
[Python] Note: A self-made function that finds the area of the normal distribution
I made a function to see the movement of a two-dimensional array (Python)
Make the Python console covered with UNKO
Create a Python function decorator with Class
Let's make a shiritori game with Python
Precautions when pickling a function in python
[Python] How to make a class iterable