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.
Needless to say this.
import inspect
inspect.isfunction(func)
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.
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
code
objectThere are the following methods as other methods. I think this is more concise.
co = getattr(func, '__code__', None)
return co != None
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__))
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