Sympy中未定义函数的类型疑问及通用识别方法咨询
Great question—this is a common point of confusion with SymPy's undefined functions, so let's unpack it clearly.
Why does type(f) seem to equal f itself?
First, let's clarify what happens when you create an undefined function in SymPy. When you run:
from sympy import Function f = Function('f')
You might notice that printing type(f) gives output like <class 'f'> instead of something like <class 'sympy.core.function.UndefinedFunction'>. This is because SymPy generates a dynamic class for each undefined function using the UndefinedFunction metaclass.
The dynamic class is named after the string you passed to Function() (in this case, 'f'), which matches the variable name you assigned it to. So when you print type(f), it shows the name of this dynamic class ('f'), which looks identical to your variable f—but they're not the same thing.
To confirm the underlying type, try checking:
from sympy.core.function import UndefinedFunction isinstance(f, UndefinedFunction) # This returns True
Here, f is an instance of the UndefinedFunction metaclass, and type(f) correctly returns the metaclass (it just displays with the dynamic class name that matches your variable).
How to generically identify undefined functions
There are two key scenarios to handle, depending on whether the function is "raw" (unapplied) or has been called with arguments (applied):
Raw undefined functions (e.g.,
f): Useisinstance()withUndefinedFunctionto check if it's a dynamic undefined function class:from sympy.core.function import UndefinedFunction def is_undefined_func(func): return isinstance(func, UndefinedFunction)This returns
Truefor any function created viaFunction('name').Applied undefined functions (e.g.,
f(x)): These are instances ofAppliedUndef, so check against that class:from sympy.core.function import AppliedUndef def is_applied_undefined_func(expr): return isinstance(expr, AppliedUndef)This works for any expression where an undefined function has been called with arguments.
Bonus: Scan expressions for any undefined functions: If you need to check if a larger expression contains any undefined functions (raw or applied), use the
has()method:from sympy import symbols x = symbols('x') (f(x) + x**2).has(UndefinedFunction, AppliedUndef) # Returns True
内容的提问来源于stack exchange,提问作者David Armendariz

