标签归档:introspection

列出给定类的层次结构中的所有基类?

问题:列出给定类的层次结构中的所有基类?

给定一个类Foo(无论它是否是新型类),如何生成所有基类-在继承层次结构中的任何位置issubclass

Given a class Foo (whether it is a new-style class or not), how do you generate all the base classes – anywhere in the inheritance hierarchy – it issubclass of?


回答 0

inspect.getmro(cls)适用于新样式和旧样式类,并以与NewClass.mro()方法解析相同的顺序返回:类及其所有祖先类的列表。

>>> class A(object):
>>>     pass
>>>
>>> class B(A):
>>>     pass
>>>
>>> import inspect
>>> inspect.getmro(B)
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)

inspect.getmro(cls) works for both new and old style classes and returns the same as NewClass.mro(): a list of the class and all its ancestor classes, in the order used for method resolution.

>>> class A(object):
>>>     pass
>>>
>>> class B(A):
>>>     pass
>>>
>>> import inspect
>>> inspect.getmro(B)
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)

回答 1

请参阅python上的可用__bases__属性class,该属性包含基类的元组:

>>> def classlookup(cls):
...     c = list(cls.__bases__)
...     for base in c:
...         c.extend(classlookup(base))
...     return c
...
>>> class A: pass
...
>>> class B(A): pass
...
>>> class C(object, B): pass
...
>>> classlookup(C)
[<type 'object'>, <class __main__.B at 0x00AB7300>, <class __main__.A at 0x00A6D630>]

See the __bases__ property available on a python class, which contains a tuple of the bases classes:

>>> def classlookup(cls):
...     c = list(cls.__bases__)
...     for base in c:
...         c.extend(classlookup(base))
...     return c
...
>>> class A: pass
...
>>> class B(A): pass
...
>>> class C(object, B): pass
...
>>> classlookup(C)
[<type 'object'>, <class __main__.B at 0x00AB7300>, <class __main__.A at 0x00A6D630>]

回答 2

inspect.getclasstree()将创建一个嵌套的类及其基列表。用法:

inspect.getclasstree(inspect.getmro(IOError)) # Insert your Class instead of IOError.

inspect.getclasstree() will create a nested list of classes and their bases. Usage:

inspect.getclasstree(inspect.getmro(IOError)) # Insert your Class instead of IOError.

回答 3

您可以使用__bases__类对象的元组:

class A(object, B, C):
    def __init__(self):
       pass
print A.__bases__

返回的元组__bases__具有其所有基类。

希望能帮助到你!

you can use the __bases__ tuple of the class object:

class A(object, B, C):
    def __init__(self):
       pass
print A.__bases__

The tuple returned by __bases__ has all its base classes.

Hope it helps!


回答 4

在python 3.7中,您无需导入inspect,type.mro将为您提供结果。

>>> class A:
...   pass
... 
>>> class B(A):
...   pass
... 
>>> type.mro(B)
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
>>>

注意,在python 3.x中,每个类都继承自基础对象类。

In python 3.7 you don’t need to import inspect, type.mro will give you the result.

>>> class A:
...   pass
... 
>>> class B(A):
...   pass
... 
>>> type.mro(B)
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
>>>

attention that in python 3.x every class inherits from base object class.


回答 5

根据Python文档,我们还可以简单地使用class.__mro__属性或class.mro()方法:

>>> class A:
...     pass
... 
>>> class B(A):
...     pass
... 
>>> B.__mro__
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
>>> A.__mro__
(<class '__main__.A'>, <class 'object'>)
>>> object.__mro__
(<class 'object'>,)
>>>
>>> B.mro()
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
>>> A.mro()
[<class '__main__.A'>, <class 'object'>]
>>> object.mro()
[<class 'object'>]
>>> A in B.mro()
True

According to the Python doc, we can also simply use class.__mro__ attribute or class.mro() method:

>>> class A:
...     pass
... 
>>> class B(A):
...     pass
... 
>>> B.__mro__
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
>>> A.__mro__
(<class '__main__.A'>, <class 'object'>)
>>> object.__mro__
(<class 'object'>,)
>>>
>>> B.mro()
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
>>> A.mro()
[<class '__main__.A'>, <class 'object'>]
>>> object.mro()
[<class 'object'>]
>>> A in B.mro()
True


回答 6

尽管Jochen的回答非常有帮助和正确,但是您可以使用inspect模块的.getmro()方法获得类层次结构,但是突出显示Python的继承层次结构也很重要:

例如:

class MyClass(YourClass):

继承类

  • 儿童班
  • 派生类
  • 子类

例如:

class YourClass(Object):

继承的类

  • 家长班
  • 基类
  • 超类

一个类可以从另一个类继承-该类的属性是继承的-特别是其方法是继承的-这意味着继承(子)类的实例可以访问该继承(父)类的属性

实例->类->然后继承的类

使用

import inspect
inspect.getmro(MyClass)

将在Python中向您显示层次结构。

Although Jochen’s answer is very helpful and correct, as you can obtain the class hierarchy using the .getmro() method of the inspect module, it’s also important to highlight that Python’s inheritance hierarchy is as follows:

ex:

class MyClass(YourClass):

An inheriting class

  • Child class
  • Derived class
  • Subclass

ex:

class YourClass(Object):

An inherited class

  • Parent class
  • Base class
  • Superclass

One class can inherit from another – The class’ attributed are inherited – in particular, its methods are inherited – this means that instances of an inheriting (child) class can access attributed of the inherited (parent) class

instance -> class -> then inherited classes

using

import inspect
inspect.getmro(MyClass)

will show you the hierarchy, within Python.


在Python中获取调用函数模块的__name__

问题:在Python中获取调用函数模块的__name__

假设myapp/foo.py包含:

def info(msg):
    caller_name = ????
    print '[%s] %s' % (caller_name, msg)

myapp/bar.py包含:

import foo
foo.info('Hello') # => [myapp.bar] Hello

在这种情况下,我想caller_name设置为“ __name__调用函数”模块的属性(即“ myapp.foo”)。如何才能做到这一点?

Suppose myapp/foo.py contains:

def info(msg):
    caller_name = ????
    print '[%s] %s' % (caller_name, msg)

And myapp/bar.py contains:

import foo
foo.info('Hello') # => [myapp.bar] Hello

I want caller_name to be set to the __name__ attribute of the calling functions’ module (which is ‘myapp.foo’) in this case. How can this be done?


回答 0

检出检查模块:

inspect.stack() 将返回堆栈信息。

在函数内部,inspect.stack()[1]将返回调用者的堆栈。从那里,您可以获得有关调用者的函数名称,模块等的更多信息。

有关详细信息,请参阅文档:

http://docs.python.org/library/inspect.html

此外,Doug Hellmann在他的PyMOTW系列中对检查模块做了很好的撰写:

http://pymotw.com/2/inspect/index.html#module-inspect

编辑:这是一些您想要的代码,我认为:

def info(msg):
    frm = inspect.stack()[1]
    mod = inspect.getmodule(frm[0])
    print '[%s] %s' % (mod.__name__, msg)

Check out the inspect module:

inspect.stack() will return the stack information.

Inside a function, inspect.stack()[1] will return your caller’s stack. From there, you can get more information about the caller’s function name, module, etc.

See the docs for details:

http://docs.python.org/library/inspect.html

Also, Doug Hellmann has a nice writeup of the inspect module in his PyMOTW series:

http://pymotw.com/2/inspect/index.html#module-inspect

EDIT: Here’s some code which does what you want, I think:

import inspect 

def info(msg):
    frm = inspect.stack()[1]
    mod = inspect.getmodule(frm[0])
    print '[%s] %s' % (mod.__name__, msg)

回答 1

面对类似的问题,我发现sys模块中的sys._current_frames()包含有趣的信息,这些信息至少在特定的用例中可以帮助您,而无需导入检查。

>>> sys._current_frames()
{4052: <frame object at 0x03200C98>}

然后,您可以使用f_back“上移”:

>>> f = sys._current_frames().values()[0]
>>> # for python3: f = list(sys._current_frames().values())[0]

>>> print f.f_back.f_globals['__file__']
'/base/data/home/apps/apricot/1.6456165165151/caller.py'

>>> print f.f_back.f_globals['__name__']
'__main__'

对于文件名,您还可以使用f.f_back.f_code.co_filename,如上文Mark Roddy所建议。我不确定此方法的局限性和注意事项(很可能会出现多个线程),但是我打算在自己的情况下使用它。

Confronted with a similar problem, I have found that sys._current_frames() from the sys module contains interesting information that can help you, without the need to import inspect, at least in specific use cases.

>>> sys._current_frames()
{4052: <frame object at 0x03200C98>}

You can then “move up” using f_back :

>>> f = sys._current_frames().values()[0]
>>> # for python3: f = list(sys._current_frames().values())[0]

>>> print f.f_back.f_globals['__file__']
'/base/data/home/apps/apricot/1.6456165165151/caller.py'

>>> print f.f_back.f_globals['__name__']
'__main__'

For the filename you can also use f.f_back.f_code.co_filename, as suggested by Mark Roddy above. I am not sure of the limits and caveats of this method (multiple threads will most likely be a problem) but I intend to use it in my case.


回答 2

我不建议您这样做,但是您可以使用以下方法来实现您的目标:

def caller_name():
    frame=inspect.currentframe()
    frame=frame.f_back.f_back
    code=frame.f_code
    return code.co_filename

然后,如下更新您的现有方法:

def info(msg):
    caller = caller_name()
    print '[%s] %s' % (caller, msg)

I don’t recommend do this, but you can accomplish your goal with the following method:

def caller_name():
    frame=inspect.currentframe()
    frame=frame.f_back.f_back
    code=frame.f_code
    return code.co_filename

Then update your existing method as follows:

def info(msg):
    caller = caller_name()
    print '[%s] %s' % (caller, msg)

如何在Python中获取类的文件路径?

问题:如何在Python中获取类的文件路径?

给定Python中的类C,如何确定该类在哪个文件中定义?我需要可以从类C或从关闭C的实例工作的东西。

之所以这样做,是因为我通常不喜欢将属于同一文件的文件放在同一文件夹中。我想创建一个使用Django模板将其自身呈现为HTML的类。基本实现应根据定义类的文件名来推断模板的文件名。

假设我在文件“ base / artifacts.py”中放置了一个LocationArtifact类,那么我希望默认行为是模板名称为“ base / LocationArtifact.html”。

Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off C.

The reason I am doing this, is because I am generally a fan off putting files that belong together in the same folder. I want to create a class that uses a Django template to render itself as HTML. The base implementation should infer the filename for the template based on the filename that the class is defined in.

Say I put a class LocationArtifact in the file “base/artifacts.py”, then I want the default behaviour to be that the template name is “base/LocationArtifact.html”.


回答 0

您可以使用检查模块,如下所示:

import inspect
inspect.getfile(C.__class__)

You can use the inspect module, like this:

import inspect
inspect.getfile(C.__class__)

回答 1

尝试:

import sys, os
os.path.abspath(sys.modules[LocationArtifact.__module__].__file__)

try:

import sys, os
os.path.abspath(sys.modules[LocationArtifact.__module__].__file__)

回答 2

对于Django而言,这是错误的方法,并且实际上是强迫的。

典型的Django应用程序模式为:

  • /项目
    • / appname
      • models.py
      • views.py
      • /模板
        • index.html
        • 等等

This is the wrong approach for Django and really forcing things.

The typical Django app pattern is:

  • /project
    • /appname
      • models.py
      • views.py
      • /templates
        • index.html
        • etc.

列出所有属于python软件包的模块吗?

问题:列出所有属于python软件包的模块吗?

有没有一种直接的方法来查找python软件包中的所有模块?我已经找到了这个旧的讨论,这并不是真正的结论,但是我很想在我基于os.listdir()推出自己的解决方案之前有一个明确的答案。

Is there a straightforward way to find all the modules that are part of a python package? I’ve found this old discussion, which is not really conclusive, but I’d love to have a definite answer before I roll out my own solution based on os.listdir().


回答 0

是的,您需要某种基于pkgutil或相似的东西-这样,您可以将所有软件包都视为相同,而不管它们是放在鸡蛋还是拉链中(在os.listdir都不起作用的地方)。

import pkgutil

# this is the package we are inspecting -- for example 'email' from stdlib
import email

package = email
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__):
    print "Found submodule %s (is a package: %s)" % (modname, ispkg)

如何导入它们呢?您可以__import__照常使用:

import pkgutil

# this is the package we are inspecting -- for example 'email' from stdlib
import email

package = email
prefix = package.__name__ + "."
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix):
    print "Found submodule %s (is a package: %s)" % (modname, ispkg)
    module = __import__(modname, fromlist="dummy")
    print "Imported", module

Yes, you want something based on pkgutil or similar — this way you can treat all packages alike regardless if they are in eggs or zips or so (where os.listdir won’t help).

import pkgutil

# this is the package we are inspecting -- for example 'email' from stdlib
import email

package = email
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__):
    print "Found submodule %s (is a package: %s)" % (modname, ispkg)

How to import them too? You can just use __import__ as normal:

import pkgutil

# this is the package we are inspecting -- for example 'email' from stdlib
import email

package = email
prefix = package.__name__ + "."
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix):
    print "Found submodule %s (is a package: %s)" % (modname, ispkg)
    module = __import__(modname, fromlist="dummy")
    print "Imported", module

回答 1

这项工作的正确工具是pkgutil.walk_packages。

要列出系统上的所有模块:

import pkgutil
for importer, modname, ispkg in pkgutil.walk_packages(path=None, onerror=lambda x: None):
    print(modname)

请注意,walk_packages会导入所有子包,但不会导入子模块。

如果您希望列出某个程序包的所有子模块,则可以使用如下代码:

import pkgutil
import scipy
package=scipy
for importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__,
                                                      prefix=package.__name__+'.',
                                                      onerror=lambda x: None):
    print(modname)

iter_modules仅列出一级深度的模块。walk_packages获取所有子模块。例如,对于scipy,walk_packages返回

scipy.stats.stats

而iter_modules仅返回

scipy.stats

pkgutil的文档(http://docs.python.org/library/pkgutil.html)没有列出/usr/lib/python2.6/pkgutil.py中定义的所有有趣功能。

也许这意味着功能不是“公共”界面的一部分,并且可能会发生变化。

但是,至少从Python 2.6起(也许是早期版本?),pkgutil带有walk_packages方法,该方法递归地遍历所有可用模块。

The right tool for this job is pkgutil.walk_packages.

To list all the modules on your system:

import pkgutil
for importer, modname, ispkg in pkgutil.walk_packages(path=None, onerror=lambda x: None):
    print(modname)

Be aware that walk_packages imports all subpackages, but not submodules.

If you wish to list all submodules of a certain package then you can use something like this:

import pkgutil
import scipy
package=scipy
for importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__,
                                                      prefix=package.__name__+'.',
                                                      onerror=lambda x: None):
    print(modname)

iter_modules only lists the modules which are one-level deep. walk_packages gets all the submodules. In the case of scipy, for example, walk_packages returns

scipy.stats.stats

while iter_modules only returns

scipy.stats

The documentation on pkgutil (http://docs.python.org/library/pkgutil.html) does not list all the interesting functions defined in /usr/lib/python2.6/pkgutil.py.

Perhaps this means the functions are not part of the “public” interface and are subject to change.

However, at least as of Python 2.6 (and perhaps earlier versions?) pkgutil comes with a walk_packages method which recursively walks through all the modules available.


回答 2

这对我有用:

import types

for key, obj in nltk.__dict__.iteritems():
    if type(obj) is types.ModuleType: 
        print key

This works for me:

import types

for key, obj in nltk.__dict__.iteritems():
    if type(obj) is types.ModuleType: 
        print key

回答 3

我一直在寻找一种方法来重新加载我正在编辑的程序包中的所有子模块。它是上述答案/评论的组合,因此我决定将其发布在此处,作为答案而不是评论。

package=yourPackageName
import importlib
import pkgutil
for importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__, prefix=package.__name__+'.', onerror=lambda x: None):
    try:
        modulesource = importlib.import_module(modname)
        reload(modulesource)
        print("reloaded: {}".format(modname))
    except Exception as e:
        print('Could not load {} {}'.format(modname, e))

I was looking for a way to reload all submodules that I’m editing live in my package. It is a combination of the answers/comments above, so I’ve decided to post it here as an answer rather than a comment.

package=yourPackageName
import importlib
import pkgutil
for importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__, prefix=package.__name__+'.', onerror=lambda x: None):
    try:
        modulesource = importlib.import_module(modname)
        reload(modulesource)
        print("reloaded: {}".format(modname))
    except Exception as e:
        print('Could not load {} {}'.format(modname, e))

回答 4

这是我的头上的一种方法:

>>> import os
>>> filter(lambda i: type(i) == type(os), [getattr(os, j) for j in dir(os)])
[<module 'UserDict' from '/usr/lib/python2.5/UserDict.pyc'>, <module 'copy_reg' from '/usr/lib/python2.5/copy_reg.pyc'>, <module 'errno' (built-in)>, <module 'posixpath' from '/usr/lib/python2.5/posixpath.pyc'>, <module 'sys' (built-in)>]

它肯定可以清理和改进。

编辑:这是一个稍微更好的版本:

>>> [m[1] for m in filter(lambda a: type(a[1]) == type(os), os.__dict__.items())]
[<module 'copy_reg' from '/usr/lib/python2.5/copy_reg.pyc'>, <module 'UserDict' from '/usr/lib/python2.5/UserDict.pyc'>, <module 'posixpath' from '/usr/lib/python2.5/posixpath.pyc'>, <module 'errno' (built-in)>, <module 'sys' (built-in)>]
>>> [m[0] for m in filter(lambda a: type(a[1]) == type(os), os.__dict__.items())]
['_copy_reg', 'UserDict', 'path', 'errno', 'sys']

注意:如果将模块拉入__init__.py文件中,它们也将找到不一定位于包子目录中的模块,因此取决于您“包的一部分”的含义。

Here’s one way, off the top of my head:

>>> import os
>>> filter(lambda i: type(i) == type(os), [getattr(os, j) for j in dir(os)])
[<module 'UserDict' from '/usr/lib/python2.5/UserDict.pyc'>, <module 'copy_reg' from '/usr/lib/python2.5/copy_reg.pyc'>, <module 'errno' (built-in)>, <module 'posixpath' from '/usr/lib/python2.5/posixpath.pyc'>, <module 'sys' (built-in)>]

It could certainly be cleaned up and improved.

EDIT: Here’s a slightly nicer version:

>>> [m[1] for m in filter(lambda a: type(a[1]) == type(os), os.__dict__.items())]
[<module 'copy_reg' from '/usr/lib/python2.5/copy_reg.pyc'>, <module 'UserDict' from '/usr/lib/python2.5/UserDict.pyc'>, <module 'posixpath' from '/usr/lib/python2.5/posixpath.pyc'>, <module 'errno' (built-in)>, <module 'sys' (built-in)>]
>>> [m[0] for m in filter(lambda a: type(a[1]) == type(os), os.__dict__.items())]
['_copy_reg', 'UserDict', 'path', 'errno', 'sys']

NOTE: This will also find modules that might not necessarily be located in a subdirectory of the package, if they’re pulled in in its __init__.py file, so it depends on what you mean by “part of” a package.


您可以列出函数接收的关键字参数吗?

问题:您可以列出函数接收的关键字参数吗?

我有一个字典,我需要将键/值作为关键字参数传递..例如。

d_args = {'kw1': 'value1', 'kw2': 'value2'}
example(**d_args)

这可以正常工作,但是如果d_args字典中有一些example函数不接受的值,则它显然会死掉。.说,如果将示例函数定义为def example(kw2):

这是一个问题,因为我无法控制d_argsexample函数的生成。它们都来自外部模块,并且example仅接受dict中的某些关键字参数。

理想情况下,我会做

parsed_kwargs = feedparser.parse(the_url)
valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2)
PyRSS2Gen.RSS2(**valid_kwargs)

我可能只是从有效的关键字参数列表中过滤出dict,但是我想知道:是否有一种方法可以以编程方式列出特定函数所采用的关键字参数?

I have a dict, which I need to pass key/values as keyword arguments.. For example..

d_args = {'kw1': 'value1', 'kw2': 'value2'}
example(**d_args)

This works fine, but if there are values in the d_args dict that are not accepted by the example function, it obviously dies.. Say, if the example function is defined as def example(kw2):

This is a problem since I don’t control either the generation of the d_args, or the example function.. They both come from external modules, and example only accepts some of the keyword-arguments from the dict..

Ideally I would just do

parsed_kwargs = feedparser.parse(the_url)
valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2)
PyRSS2Gen.RSS2(**valid_kwargs)

I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: Is there a way to programatically list the keyword arguments the a specific function takes?


回答 0

比起直接检查代码对象并计算出变量,更好的方法是使用检查模块。

>>> import inspect
>>> def func(a,b,c=42, *args, **kwargs): pass
>>> inspect.getargspec(func)
(['a', 'b', 'c'], 'args', 'kwargs', (42,))

如果您想知道它是否可以与一组特定的args一起调用,则需要未指定默认值的args。这些可以通过以下方式获得:

def getRequiredArgs(func):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if defaults:
        args = args[:-len(defaults)]
    return args   # *args and **kwargs are not required, so ignore them.

然后一个函数来告诉您特定字典缺少什么:

def missingArgs(func, argdict):
    return set(getRequiredArgs(func)).difference(argdict)

同样,要检查无效的参数,请使用:

def invalidArgs(func, argdict):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if varkw: return set()  # All accepted
    return set(argdict) - set(args)

因此,是否可以调用的完整测试是:

def isCallableWithArgs(func, argdict):
    return not missingArgs(func, argdict) and not invalidArgs(func, argdict)

(这仅在python的arg解析方面是好的。任何运行时检查kwargs中的无效值显然都无法检测到。)

A little nicer than inspecting the code object directly and working out the variables is to use the inspect module.

>>> import inspect
>>> def func(a,b,c=42, *args, **kwargs): pass
>>> inspect.getargspec(func)
(['a', 'b', 'c'], 'args', 'kwargs', (42,))

If you want to know if its callable with a particular set of args, you need the args without a default already specified. These can be got by:

def getRequiredArgs(func):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if defaults:
        args = args[:-len(defaults)]
    return args   # *args and **kwargs are not required, so ignore them.

Then a function to tell what you are missing from your particular dict is:

def missingArgs(func, argdict):
    return set(getRequiredArgs(func)).difference(argdict)

Similarly, to check for invalid args, use:

def invalidArgs(func, argdict):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if varkw: return set()  # All accepted
    return set(argdict) - set(args)

And so a full test if it is callable is :

def isCallableWithArgs(func, argdict):
    return not missingArgs(func, argdict) and not invalidArgs(func, argdict)

(This is good only as far as python’s arg parsing. Any runtime checks for invalid values in kwargs obviously can’t be detected.)


回答 1

这将打印所有可传递参数,关键字和非关键字参数的名称:

def func(one, two="value"):
    y = one, two
    return y
print func.func_code.co_varnames[:func.func_code.co_argcount]

这是因为第一个co_varnames始终是参数(下一个是局部变量,y如上例所示)。

所以现在您可以拥有一个功能:

def getValidArgs(func, argsDict):
    '''Return dictionary without invalid function arguments.'''
    validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]
    return dict((key, value) for key, value in argsDict.iteritems() 
                if key in validArgs)

然后可以这样使用:

>>> func(**getValidArgs(func, args))

编辑:一个小的补充:如果您真的只需要一个函数的关键字参数,则可以使用func_defaults属性来提取它们:

def getValidKwargs(func, argsDict):
    validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]
    kwargsLen = len(func.func_defaults) # number of keyword arguments
    validKwargs = validArgs[-kwargsLen:] # because kwargs are last
    return dict((key, value) for key, value in argsDict.iteritems() 
                if key in validKwargs)

现在,您可以使用已知的args调用函数,但是要提取kwargs,例如:

func(param1, param2, **getValidKwargs(func, kwargsDict))

假定签名中func不使用no *args**kwargsmagic。

This will print names of all passable arguments, keyword and non-keyword ones:

def func(one, two="value"):
    y = one, two
    return y
print func.func_code.co_varnames[:func.func_code.co_argcount]

This is because first co_varnames are always parameters (next are local variables, like y in the example above).

So now you could have a function:

def getValidArgs(func, argsDict):
    '''Return dictionary without invalid function arguments.'''
    validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]
    return dict((key, value) for key, value in argsDict.iteritems() 
                if key in validArgs)

Which you then could use like this:

>>> func(**getValidArgs(func, args))

EDIT: A small addition: if you really need only keyword arguments of a function, you can use the func_defaults attribute to extract them:

def getValidKwargs(func, argsDict):
    validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]
    kwargsLen = len(func.func_defaults) # number of keyword arguments
    validKwargs = validArgs[-kwargsLen:] # because kwargs are last
    return dict((key, value) for key, value in argsDict.iteritems() 
                if key in validKwargs)

You could now call your function with known args, but extracted kwargs, e.g.:

func(param1, param2, **getValidKwargs(func, kwargsDict))

This assumes that func uses no *args or **kwargs magic in its signature.


回答 2

在Python 3.0中:

>>> import inspect
>>> import fileinput
>>> print(inspect.getfullargspec(fileinput.input))
FullArgSpec(args=['files', 'inplace', 'backup', 'bufsize', 'mode', 'openhook'],
varargs=None, varkw=None, defaults=(None, 0, '', 0, 'r', None), kwonlyargs=[], 
kwdefaults=None, annotations={})

In Python 3.0:

>>> import inspect
>>> import fileinput
>>> print(inspect.getfullargspec(fileinput.input))
FullArgSpec(args=['files', 'inplace', 'backup', 'bufsize', 'mode', 'openhook'],
varargs=None, varkw=None, defaults=(None, 0, '', 0, 'r', None), kwonlyargs=[], 
kwdefaults=None, annotations={})

回答 3

对于Python 3解决方案,您可以inspect.signature根据想要了解的参数种类使用和过滤。

以带有位置或关键字,仅关键字,var positional和var关键字参数的样本函数为例:

def spam(a, b=1, *args, c=2, **kwargs):
    print(a, b, args, c, kwargs)

您可以为其创建签名对象:

from inspect import signature
sig =  signature(spam)

然后使用列表推导进行过滤以找出所需的详细信息:

>>> # positional or keyword
>>> [p.name for p in sig.parameters.values() if p.kind == p.POSITIONAL_OR_KEYWORD]
['a', 'b']
>>> # keyword only
>>> [p.name for p in sig.parameters.values() if p.kind == p.KEYWORD_ONLY]
['c']

同样,对于使用p.VAR_POSITIONALvar关键字和var关键字与的变量VAR_KEYWORD

另外,您可以在if中添加一个子句,以通过检查是否p.default等于来检查是否存在默认值p.empty

For a Python 3 solution, you can use inspect.signature and filter according to the kind of parameters you’d like to know about.

Taking a sample function with positional or keyword, keyword-only, var positional and var keyword parameters:

def spam(a, b=1, *args, c=2, **kwargs):
    print(a, b, args, c, kwargs)

You can create a signature object for it:

from inspect import signature
sig =  signature(spam)

and then filter with a list comprehension to find out the details you need:

>>> # positional or keyword
>>> [p.name for p in sig.parameters.values() if p.kind == p.POSITIONAL_OR_KEYWORD]
['a', 'b']
>>> # keyword only
>>> [p.name for p in sig.parameters.values() if p.kind == p.KEYWORD_ONLY]
['c']

and, similarly, for var positionals using p.VAR_POSITIONAL and var keyword with VAR_KEYWORD.

In addition, you can add a clause to the if to check if a default value exists by checking if p.default equals p.empty.


回答 4

扩展DzinX的答案:

argnames = example.func_code.co_varnames[:func.func_code.co_argcount]
args = dict((key, val) for key,val in d_args.iteritems() if key in argnames)
example(**args)

Extending DzinX’s answer:

argnames = example.func_code.co_varnames[:func.func_code.co_argcount]
args = dict((key, val) for key,val in d_args.iteritems() if key in argnames)
example(**args)

斜杠在help()输出中意味着什么?

问题:斜杠在help()输出中意味着什么?

在闭括号前/,Python 3.4的help输出是什么意思range

>>> help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |  
 |  Return a virtual sequence of numbers from start to stop by step.
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.

                                        ...

What does the / mean in Python 3.4’s help output for range before the closing parenthesis?

>>> help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |  
 |  Return a virtual sequence of numbers from start to stop by step.
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.

                                        ...

回答 0

它象征着结束位置唯一参数,参数,你不能作为关键字参数使用。在Python 3.8之前,只能在C API中指定此类参数。

这意味着keyto 的参数__contains__只能通过position(range(5).__contains__(3))传递,而不能作为关键字参数(range(5).__contains__(key=3))传递,这可以通过pure-python函数中的position参数完成。

另请参阅Argument Clinic文档:

要将所有参数标记为Argument Clinic中的“仅位置”,请/在最后一个参数之后单独添加一行,并使其与参数行缩进。

和(最近添加的)Python FAQ

函数的参数列表中的斜杠表示该函数之前的参数仅是位置参数。仅位置参数是没有外部可用名称的参数。调用仅接受位置参数的函数后,参数将仅基于其位置映射到参数。

3.8版开始,该语法现已成为Python语言规范的一部分,请参阅PEP 570 – 仅Python位置参数。在PEP 570之前,已经保留了该语法以供将来将来包含在Python中,请参阅PEP 457- 仅位置参数的语法

仅位置参数可以导致更清晰的API,使原本仅C语言的模块的纯Python实现更加一致且易于维护,并且由于仅位置参数需要很少的处理,因此它们可导致更快的Python代码。

It signifies the end of the positional only parameters, parameters you cannot use as keyword parameters. Before Python 3.8, such parameters could only be specified in the C API.

It means the key argument to __contains__ can only be passed in by position (range(5).__contains__(3)), not as a keyword argument (range(5).__contains__(key=3)), something you can do with positional arguments in pure-python functions.

Also see the Argument Clinic documentation:

To mark all parameters as positional-only in Argument Clinic, add a / on a line by itself after the last parameter, indented the same as the parameter lines.

and the (very recent addition to) the Python FAQ:

A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position.

The syntax is now part of the Python language specification, as of version 3.8, see PEP 570 – Python Positional-Only Parameters. Before PEP 570, the syntax was already reserved for possible future inclusion in Python, see PEP 457 – Syntax For Positional-Only Parameters.

Positional-only parameters can lead to cleaner and clearer APIs, make pure-Python implementations of otherwise C-only modules more consistent and easier to maintain, and because positional-only parameters require very little processing, they lead to faster Python code.


回答 1

我自己问了这个问题。:)发现这/是Guido最初在这里提出的。

替代方案:使用’/’怎么样?它与“ *”相反,后者表示“关键字参数”,而“ /”不是新字符。

然后他的提议获胜

嘿。如果是这样,我的“ /”建议将获胜:

 def foo(pos_only, /, pos_or_kw, *, kw_only): ...

我认为涉及此的非常相关的文件是PEP 570。回顾部分看起来不错。

回顾

用例将确定在函数定义中使用哪些参数:

 def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):

作为指导:

仅在名称无关紧要或名称没有含义且仅会以相同顺序传递少数参数的情况下,才使用仅位置。当名称具有含义且通过使用名称明确表示功能定义时,请仅使用关键字。


如果函数以 /

def foo(p1, p2, /)

这意味着所有功能参数都是位置性的。

I asked this question myself. :) Found out that / was originally proposed by Guido in here.

Alternative proposal: how about using ‘/’ ? It’s kind of the opposite of ‘*’ which means “keyword argument”, and ‘/’ is not a new character.

Then his proposal won.

Heh. If that’s true, my ‘/’ proposal wins:

 def foo(pos_only, /, pos_or_kw, *, kw_only): ...

I think the very relevant document covering this is PEP 570. Where recap section looks nice.

Recap

The use case will determine which parameters to use in the function definition:

 def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):

As guidance:

Use positional-only if names do not matter or have no meaning, and there are only a few arguments which will always be passed in the same order. Use keyword-only when names have meaning and the function definition is more understandable by being explicit with names.


If the function ends with /

def foo(p1, p2, /)

This means all functional arguments are positional.


回答 2

正斜杠(/)表示之前的所有参数都是位置唯一的参数。在接受PEP 570之后,在python 3.8中添加了仅位置参数功能。最初,此表示法是在PEP 457-仅位置参数表示法中定义的

在函数定义中,Foraward斜杠(/)之前的参数仅是位置参数,后跟斜杠(/)的参数根据语法可以是任何种类。仅在调用函数时根据参数的位置将参数映射到仅位置参数。通过关键字(名称)传递仅位置参数无效。

让我们来看下面的例子

def foo(a, b, / , x, y):
   print("positional ", a, b)
   print("positional or keyword", x, y)

在上面的函数定义中,参数a和b仅是位置信息,而x或y可以是位置信息或关键字。

以下函数调用有效

foo(40, 20, 99, 39)
foo(40, 3.14, "hello", y="world")
foo(1.45, 3.14, x="hello", y="world")

但是,以下函数调用无效,从而引发TypeError异常,因为a,b没有作为位置参数传递,而是作为关键字传递

foo(a=1.45, b=3.14, x=1, y=4)

TypeError:foo()获得了一些仅位置参数作为关键字参数传递:’a,b’

python中的许多内置函数仅接受位置参数,而按关键字传递参数没有意义。例如,内置函数len仅接受一个positional(only)参数,如果将len调用为len(obj =“ hello world”)会损害可读性,则检查help(len)。

>>> help(len)
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

仅位置参数使基础c /库函数易于维护。它允许将来仅更改位置参数的参数名称,而不会破坏使用API​​的客户端代码的风险

最后但并非最不重要的一点是,仅位置参数允许我们使用其名称在可变长度关键字参数中使用。检查以下示例

>>> def f(a, b, /, **kwargs):
...     print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3)         # a and b are used in two ways
10 20 {'a': 1, 'b': 2, 'c': 3}

仅位置参数比较好此处在python中的函数参数类型中进行了解释:仅位置参数

仅位置参数语法已正式添加到python3.8中。签出python3.8的新功能-仅位置参数

与PEP相关:PEP 570-Python仅位置参数

Forward Slash (/) indicates all arguments prior to it are positional only argument. Positional only arguments feature was added in python 3.8 after PEP 570 was accepted. Initially this notation was defined in PEP 457 – Notation for Notation For Positional-Only Parameters

Parameters in function definition prior Foraward slash (/) are positional only and parameters followed by slash(/) can be of any kind as per syntax. Where arguments are mapped to positional only parameters solely based on their position upon calling a function. Passing positional-only parameters by keywords(name) is invalid.

Let’s take following example

def foo(a, b, / , x, y):
   print("positional ", a, b)
   print("positional or keyword", x, y)

Here in the above function definition parameters a and b are positional-only, while x or y can be either positional or keyword.

Following function calls are valid

foo(40, 20, 99, 39)
foo(40, 3.14, "hello", y="world")
foo(1.45, 3.14, x="hello", y="world")

But, following function call is not valid which raises an exception TypeError since a, b are not passed as positional arguments instead passed as keyword

foo(a=1.45, b=3.14, x=1, y=4)

TypeError: foo() got some positional-only arguments passed as keyword arguments: ‘a, b’

Many built in function in python accept positional only arguments where passing arguments by keyword doesn’t make sense. For example built-in function len accepts only one positional(only) argument, Where calling len as len(obj=”hello world”) impairs readability, check help(len).

>>> help(len)
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

Positional only parameters make underlying c/library functions easy to maintain. It allows parameters names of positional only parameters to be changes in future without risk of breaking client code that uses API

Last but not least, positional only parameters allow us to use their names to be used in variable length keyword arguments. Check following example

>>> def f(a, b, /, **kwargs):
...     print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3)         # a and b are used in two ways
10 20 {'a': 1, 'b': 2, 'c': 3}

Positional only parameters is better Explained here at Types of function arguments in python: Positional Only Parameters

Positional-only parameters syntax was officially added to python3.8. Checkout what’s new python3.8 – positional only arguments

PEP Related: PEP 570 — Python Positional-Only Parameters


如何在被调用方法中获取调用者的方法名称?

问题:如何在被调用方法中获取调用者的方法名称?

Python:如何在被调用方法中获取调用者的方法名称?

假设我有2种方法:

def method1(self):
    ...
    a = A.method2()

def method2(self):
    ...

如果我不想对method1进行任何更改,如何在method2中获取调用者的名称(在本示例中,名称为method1)?

Python: How to get the caller’s method name in the called method?

Assume I have 2 methods:

def method1(self):
    ...
    a = A.method2()

def method2(self):
    ...

If I don’t want to do any change for method1, how to get the name of the caller (in this example, the name is method1) in method2?


回答 0

inspect.getframeinfo和其他相关功能inspect可以帮助:

>>> import inspect
>>> def f1(): f2()
... 
>>> def f2():
...   curframe = inspect.currentframe()
...   calframe = inspect.getouterframes(curframe, 2)
...   print('caller name:', calframe[1][3])
... 
>>> f1()
caller name: f1

该自省旨在帮助调试和开发;建议不要出于生产功能目的而依赖它。

inspect.getframeinfo and other related functions in inspect can help:

>>> import inspect
>>> def f1(): f2()
... 
>>> def f2():
...   curframe = inspect.currentframe()
...   calframe = inspect.getouterframes(curframe, 2)
...   print('caller name:', calframe[1][3])
... 
>>> f1()
caller name: f1

this introspection is intended to help debugging and development; it’s not advisable to rely on it for production-functionality purposes.


回答 1

较短的版本:

import inspect

def f1(): f2()

def f2():
    print 'caller name:', inspect.stack()[1][3]

f1()

(感谢@Alex和Stefaan Lippen

Shorter version:

import inspect

def f1(): f2()

def f2():
    print 'caller name:', inspect.stack()[1][3]

f1()

(with thanks to @Alex, and Stefaan Lippen)


回答 2

这似乎很好用:

import sys
print sys._getframe().f_back.f_code.co_name

This seems to work just fine:

import sys
print sys._getframe().f_back.f_code.co_name

回答 3

我想出了一个稍长的版本,试图建立一个完整的方法名称,包括模块和类。

https://gist.github.com/2151727(rev 9cccbf)

# Public Domain, i.e. feel free to copy/paste
# Considered a hack in Python 2

import inspect

def caller_name(skip=2):
    """Get a name of a caller in the format module.class.method

       `skip` specifies how many levels of stack to skip while getting caller
       name. skip=1 means "who calls me", skip=2 "who calls my caller" etc.

       An empty string is returned if skipped levels exceed stack height
    """
    stack = inspect.stack()
    start = 0 + skip
    if len(stack) < start + 1:
      return ''
    parentframe = stack[start][0]    

    name = []
    module = inspect.getmodule(parentframe)
    # `modname` can be None when frame is executed directly in console
    # TODO(techtonik): consider using __main__
    if module:
        name.append(module.__name__)
    # detect classname
    if 'self' in parentframe.f_locals:
        # I don't know any way to detect call from the object method
        # XXX: there seems to be no way to detect static method call - it will
        #      be just a function call
        name.append(parentframe.f_locals['self'].__class__.__name__)
    codename = parentframe.f_code.co_name
    if codename != '<module>':  # top level usually
        name.append( codename ) # function or a method

    ## Avoid circular refs and frame leaks
    #  https://docs.python.org/2.7/library/inspect.html#the-interpreter-stack
    del parentframe, stack

    return ".".join(name)

I’ve come up with a slightly longer version that tries to build a full method name including module and class.

https://gist.github.com/2151727 (rev 9cccbf)

# Public Domain, i.e. feel free to copy/paste
# Considered a hack in Python 2

import inspect

def caller_name(skip=2):
    """Get a name of a caller in the format module.class.method

       `skip` specifies how many levels of stack to skip while getting caller
       name. skip=1 means "who calls me", skip=2 "who calls my caller" etc.

       An empty string is returned if skipped levels exceed stack height
    """
    stack = inspect.stack()
    start = 0 + skip
    if len(stack) < start + 1:
      return ''
    parentframe = stack[start][0]    

    name = []
    module = inspect.getmodule(parentframe)
    # `modname` can be None when frame is executed directly in console
    # TODO(techtonik): consider using __main__
    if module:
        name.append(module.__name__)
    # detect classname
    if 'self' in parentframe.f_locals:
        # I don't know any way to detect call from the object method
        # XXX: there seems to be no way to detect static method call - it will
        #      be just a function call
        name.append(parentframe.f_locals['self'].__class__.__name__)
    codename = parentframe.f_code.co_name
    if codename != '<module>':  # top level usually
        name.append( codename ) # function or a method

    ## Avoid circular refs and frame leaks
    #  https://docs.python.org/2.7/library/inspect.html#the-interpreter-stack
    del parentframe, stack

    return ".".join(name)

回答 4

我会用inspect.currentframe().f_back.f_code.co_name。先前的任何答案都未涵盖其使用,这些答案主要是以下三种类型之一:

  • 使用一些先前的答案,inspect.stack但已知它太慢
  • 一些先前的答案使用 sys._getframe是给定其下划线的内部私有函数,因此不建议使用它。
  • 使用一个先前的答案,inspect.getouterframes(inspect.currentframe(), 2)[1][3]但是完全不清楚[1][3]正在访问什么。
import inspect
from types import FrameType
from typing import cast


def caller_name() -> str:
    """Return the calling function's name."""
    # Ref: https://stackoverflow.com/a/57712700/
    return cast(FrameType, cast(FrameType, inspect.currentframe()).f_back).f_code.co_name


if __name__ == '__main__':
    def _test_caller_name() -> None:
        assert caller_name() == '_test_caller_name'
    _test_caller_name()

请注意,cast(FrameType, frame)用于满足mypy


致谢:1313e事先发表评论以寻求答案

I would use inspect.currentframe().f_back.f_code.co_name. Its use hasn’t been covered in any of the prior answers which are mainly of one of three types:

  • Some prior answers use inspect.stack but it’s known to be too slow.
  • Some prior answers use sys._getframe which is an internal private function given its leading underscore, and so its use is implicitly discouraged.
  • One prior answer uses inspect.getouterframes(inspect.currentframe(), 2)[1][3] but it’s entirely unclear what [1][3] is accessing.
import inspect
from types import FrameType
from typing import cast


def caller_name() -> str:
    """Return the calling function's name."""
    # Ref: https://stackoverflow.com/a/57712700/
    return cast(FrameType, cast(FrameType, inspect.currentframe()).f_back).f_code.co_name


if __name__ == '__main__':
    def _test_caller_name() -> None:
        assert caller_name() == '_test_caller_name'
    _test_caller_name()

Note that cast(FrameType, frame) is used to satisfy mypy.


Acknowlegement: prior comment by 1313e for an answer.


回答 5

上面的东西有点融合。但是,这是我的努力。

def print_caller_name(stack_size=3):
    def wrapper(fn):
        def inner(*args, **kwargs):
            import inspect
            stack = inspect.stack()

            modules = [(index, inspect.getmodule(stack[index][0]))
                       for index in reversed(range(1, stack_size))]
            module_name_lengths = [len(module.__name__)
                                   for _, module in modules]

            s = '{index:>5} : {module:^%i} : {name}' % (max(module_name_lengths) + 4)
            callers = ['',
                       s.format(index='level', module='module', name='name'),
                       '-' * 50]

            for index, module in modules:
                callers.append(s.format(index=index,
                                        module=module.__name__,
                                        name=stack[index][3]))

            callers.append(s.format(index=0,
                                    module=fn.__module__,
                                    name=fn.__name__))
            callers.append('')
            print('\n'.join(callers))

            fn(*args, **kwargs)
        return inner
    return wrapper

用:

@print_caller_name(4)
def foo():
    return 'foobar'

def bar():
    return foo()

def baz():
    return bar()

def fizz():
    return baz()

fizz()

输出是

level :             module             : name
--------------------------------------------------
    3 :              None              : fizz
    2 :              None              : baz
    1 :              None              : bar
    0 :            __main__            : foo

Bit of an amalgamation of the stuff above. But here’s my crack at it.

def print_caller_name(stack_size=3):
    def wrapper(fn):
        def inner(*args, **kwargs):
            import inspect
            stack = inspect.stack()

            modules = [(index, inspect.getmodule(stack[index][0]))
                       for index in reversed(range(1, stack_size))]
            module_name_lengths = [len(module.__name__)
                                   for _, module in modules]

            s = '{index:>5} : {module:^%i} : {name}' % (max(module_name_lengths) + 4)
            callers = ['',
                       s.format(index='level', module='module', name='name'),
                       '-' * 50]

            for index, module in modules:
                callers.append(s.format(index=index,
                                        module=module.__name__,
                                        name=stack[index][3]))

            callers.append(s.format(index=0,
                                    module=fn.__module__,
                                    name=fn.__name__))
            callers.append('')
            print('\n'.join(callers))

            fn(*args, **kwargs)
        return inner
    return wrapper

Use:

@print_caller_name(4)
def foo():
    return 'foobar'

def bar():
    return foo()

def baz():
    return bar()

def fizz():
    return baz()

fizz()

output is

level :             module             : name
--------------------------------------------------
    3 :              None              : fizz
    2 :              None              : baz
    1 :              None              : bar
    0 :            __main__            : foo

回答 6

我发现了一种方法,如果您要遍历类,并希望该方法所属的类与该方法相对应。它需要一些提取工作,但很重要。这在Python 2.7.13中有效。

import inspect, os

class ClassOne:
    def method1(self):
        classtwoObj.method2()

class ClassTwo:
    def method2(self):
        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 4)
        print '\nI was called from', calframe[1][3], \
        'in', calframe[1][4][0][6: -2]

# create objects to access class methods
classoneObj = ClassOne()
classtwoObj = ClassTwo()

# start the program
os.system('cls')
classoneObj.method1()

I found a way if you’re going across classes and want the class the method belongs to AND the method. It takes a bit of extraction work but it makes its point. This works in Python 2.7.13.

import inspect, os

class ClassOne:
    def method1(self):
        classtwoObj.method2()

class ClassTwo:
    def method2(self):
        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 4)
        print '\nI was called from', calframe[1][3], \
        'in', calframe[1][4][0][6: -2]

# create objects to access class methods
classoneObj = ClassOne()
classtwoObj = ClassTwo()

# start the program
os.system('cls')
classoneObj.method1()

回答 7

#!/usr/bin/env python
import inspect

called=lambda: inspect.stack()[1][3]

def caller1():
    print "inside: ",called()

def caller2():
    print "inside: ",called()

if __name__=='__main__':
    caller1()
    caller2()
shahid@shahid-VirtualBox:~/Documents$ python test_func.py 
inside:  caller1
inside:  caller2
shahid@shahid-VirtualBox:~/Documents$
#!/usr/bin/env python
import inspect

called=lambda: inspect.stack()[1][3]

def caller1():
    print "inside: ",called()

def caller2():
    print "inside: ",called()

if __name__=='__main__':
    caller1()
    caller2()
shahid@shahid-VirtualBox:~/Documents$ python test_func.py 
inside:  caller1
inside:  caller2
shahid@shahid-VirtualBox:~/Documents$

如何获取方法参数名称?

问题:如何获取方法参数名称?

鉴于Python函数:

def a_method(arg1, arg2):
    pass

如何提取参数的数量和名称。即,鉴于我有提及func,因此我希望func.[something]返回("arg1", "arg2")

这样做的使用场景是我有一个装饰器,并且我希望以与实际函数作为键一样的顺序使用方法参数。即,"a,b"我调用时装饰工的外观如何a_method("a", "b")

Given the Python function:

def a_method(arg1, arg2):
    pass

How can I extract the number and names of the arguments. I.e., given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2").

The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. I.e., how would the decorator look that printed "a,b" when I call a_method("a", "b")?


回答 0

看一下inspect模块-这将为您检查各种代码对象属性。

>>> inspect.getfullargspec(a_method)
(['arg1', 'arg2'], None, None, None)

其他结果是* args和** kwargs变量的名称,以及提供的默认值。即。

>>> def foo(a, b, c=4, *arglist, **keywords): pass
>>> inspect.getfullargspec(foo)
(['a', 'b', 'c'], 'arglist', 'keywords', (4,))

请注意,在某些Python实现中,某些可调用对象可能不是自省的。例如,在CPython中,C中定义的某些内置函数不提供有关其参数的元数据。结果,ValueError如果您inspect.getfullargspec()在内置函数上使用,将得到一个。

从Python 3.3开始,您可以inspect.signature()用来查看可调用对象的调用签名:

>>> inspect.signature(foo)
<Signature (a, b, c=4, *arglist, **keywords)>

Take a look at the inspect module – this will do the inspection of the various code object properties for you.

>>> inspect.getfullargspec(a_method)
(['arg1', 'arg2'], None, None, None)

The other results are the name of the *args and **kwargs variables, and the defaults provided. ie.

>>> def foo(a, b, c=4, *arglist, **keywords): pass
>>> inspect.getfullargspec(foo)
(['a', 'b', 'c'], 'arglist', 'keywords', (4,))

Note that some callables may not be introspectable in certain implementations of Python. For Example, in CPython, some built-in functions defined in C provide no metadata about their arguments. As a result, you will get a ValueError if you use inspect.getfullargspec() on a built-in function.

Since Python 3.3, you can use inspect.signature() to see the call signature of a callable object:

>>> inspect.signature(foo)
<Signature (a, b, c=4, *arglist, **keywords)>

回答 1

在CPython中,参数数量为

a_method.func_code.co_argcount

他们的名字在

a_method.func_code.co_varnames

这些是CPython的实现细节,因此在其他Python实现(例如IronPython和Jython)中可能不起作用。

接受“传递”参数的一种可移植方式是使用签名定义函数func(*args, **kwargs)。这在matplotlib中经常使用,其中外部API层将许多关键字参数传递给较低级别​​的API。

In CPython, the number of arguments is

a_method.func_code.co_argcount

and their names are in the beginning of

a_method.func_code.co_varnames

These are implementation details of CPython, so this probably does not work in other implementations of Python, such as IronPython and Jython.

One portable way to admit “pass-through” arguments is to define your function with the signature func(*args, **kwargs). This is used a lot in e.g. matplotlib, where the outer API layer passes lots of keyword arguments to the lower-level API.


回答 2

在装饰器方法中,可以通过以下方式列出原始方法的参数:

import inspect, itertools 

def my_decorator():

        def decorator(f):

            def wrapper(*args, **kwargs):

                # if you want arguments names as a list:
                args_name = inspect.getargspec(f)[0]
                print(args_name)

                # if you want names and values as a dictionary:
                args_dict = dict(itertools.izip(args_name, args))
                print(args_dict)

                # if you want values as a list:
                args_values = args_dict.values()
                print(args_values)

如果**kwargs对您来说很重要,那么它将有些复杂:

        def wrapper(*args, **kwargs):

            args_name = list(OrderedDict.fromkeys(inspect.getargspec(f)[0] + kwargs.keys()))
            args_dict = OrderedDict(list(itertools.izip(args_name, args)) + list(kwargs.iteritems()))
            args_values = args_dict.values()

例:

@my_decorator()
def my_function(x, y, z=3):
    pass


my_function(1, y=2, z=3, w=0)
# prints:
# ['x', 'y', 'z', 'w']
# {'y': 2, 'x': 1, 'z': 3, 'w': 0}
# [1, 2, 3, 0]

In a decorator method, you can list arguments of the original method in this way:

import inspect, itertools 

def my_decorator():

        def decorator(f):

            def wrapper(*args, **kwargs):

                # if you want arguments names as a list:
                args_name = inspect.getargspec(f)[0]
                print(args_name)

                # if you want names and values as a dictionary:
                args_dict = dict(itertools.izip(args_name, args))
                print(args_dict)

                # if you want values as a list:
                args_values = args_dict.values()
                print(args_values)

If the **kwargs are important for you, then it will be a bit complicated:

        def wrapper(*args, **kwargs):

            args_name = list(OrderedDict.fromkeys(inspect.getargspec(f)[0] + kwargs.keys()))
            args_dict = OrderedDict(list(itertools.izip(args_name, args)) + list(kwargs.iteritems()))
            args_values = args_dict.values()

Example:

@my_decorator()
def my_function(x, y, z=3):
    pass


my_function(1, y=2, z=3, w=0)
# prints:
# ['x', 'y', 'z', 'w']
# {'y': 2, 'x': 1, 'z': 3, 'w': 0}
# [1, 2, 3, 0]

回答 3

我认为您要寻找的是locals方法-


In [6]: def test(a, b):print locals()
   ...: 

In [7]: test(1,2)              
{'a': 1, 'b': 2}

I think what you’re looking for is the locals method –


In [6]: def test(a, b):print locals()
   ...: 

In [7]: test(1,2)              
{'a': 1, 'b': 2}

回答 4

Python 3版本是:

def _get_args_dict(fn, args, kwargs):
    args_names = fn.__code__.co_varnames[:fn.__code__.co_argcount]
    return {**dict(zip(args_names, args)), **kwargs}

该方法返回一个包含args和kwargs的字典。

The Python 3 version is:

def _get_args_dict(fn, args, kwargs):
    args_names = fn.__code__.co_varnames[:fn.__code__.co_argcount]
    return {**dict(zip(args_names, args)), **kwargs}

The method returns a dictionary containing both args and kwargs.


回答 5

我认为这可以使用装饰器满足您的需求。

class LogWrappedFunction(object):
    def __init__(self, function):
        self.function = function

    def logAndCall(self, *arguments, **namedArguments):
        print "Calling %s with arguments %s and named arguments %s" %\
                      (self.function.func_name, arguments, namedArguments)
        self.function.__call__(*arguments, **namedArguments)

def logwrap(function):
    return LogWrappedFunction(function).logAndCall

@logwrap
def doSomething(spam, eggs, foo, bar):
    print "Doing something totally awesome with %s and %s." % (spam, eggs)


doSomething("beans","rice", foo="wiggity", bar="wack")

运行它,将产生以下输出:

C:\scripts>python decoratorExample.py
Calling doSomething with arguments ('beans', 'rice') and named arguments {'foo':
 'wiggity', 'bar': 'wack'}
Doing something totally awesome with beans and rice.

Here is something I think will work for what you want, using a decorator.

class LogWrappedFunction(object):
    def __init__(self, function):
        self.function = function

    def logAndCall(self, *arguments, **namedArguments):
        print "Calling %s with arguments %s and named arguments %s" %\
                      (self.function.func_name, arguments, namedArguments)
        self.function.__call__(*arguments, **namedArguments)

def logwrap(function):
    return LogWrappedFunction(function).logAndCall

@logwrap
def doSomething(spam, eggs, foo, bar):
    print "Doing something totally awesome with %s and %s." % (spam, eggs)


doSomething("beans","rice", foo="wiggity", bar="wack")

Run it, it will yield the following output:

C:\scripts>python decoratorExample.py
Calling doSomething with arguments ('beans', 'rice') and named arguments {'foo':
 'wiggity', 'bar': 'wack'}
Doing something totally awesome with beans and rice.

回答 6

Python 3.5以上版本:

DeprecationWarning:不建议使用inspect.getargspec(),而应使用inspect.signature()代替

所以以前:

func_args = inspect.getargspec(function).args

现在:

func_args = list(inspect.signature(function).parameters.keys())

去测试:

'arg' in list(inspect.signature(function).parameters.keys())

假设我们有函数’function’接受参数’arg’,则其求值为True,否则为False。

来自Python控制台的示例:

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
>>> import inspect
>>> 'iterable' in list(inspect.signature(sum).parameters.keys())
True

Python 3.5+:

DeprecationWarning: inspect.getargspec() is deprecated, use inspect.signature() instead

So previously:

func_args = inspect.getargspec(function).args

Now:

func_args = list(inspect.signature(function).parameters.keys())

To test:

'arg' in list(inspect.signature(function).parameters.keys())

Given that we have function ‘function’ which takes argument ‘arg’, this will evaluate as True, otherwise as False.

Example from the Python console:

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
>>> import inspect
>>> 'iterable' in list(inspect.signature(sum).parameters.keys())
True

回答 7

在带有Signature对象的Python 3. +中,一种获取参数名称与值之间映射的简单方法是使用Signature的bind()方法!

例如,以下是一个装饰器,用于打印类似的地图:

import inspect

def decorator(f):
    def wrapper(*args, **kwargs):
        bound_args = inspect.signature(f).bind(*args, **kwargs)
        bound_args.apply_defaults()
        print(dict(bound_args.arguments))

        return f(*args, **kwargs)

    return wrapper

@decorator
def foo(x, y, param_with_default="bars", **kwargs):
    pass

foo(1, 2, extra="baz")
# This will print: {'kwargs': {'extra': 'baz'}, 'param_with_default': 'bars', 'y': 2, 'x': 1}

In Python 3.+ with the Signature object at hand, an easy way to get a mapping between argument names to values, is using the Signature’s bind() method!

For example, here is a decorator for printing a map like that:

import inspect

def decorator(f):
    def wrapper(*args, **kwargs):
        bound_args = inspect.signature(f).bind(*args, **kwargs)
        bound_args.apply_defaults()
        print(dict(bound_args.arguments))

        return f(*args, **kwargs)

    return wrapper

@decorator
def foo(x, y, param_with_default="bars", **kwargs):
    pass

foo(1, 2, extra="baz")
# This will print: {'kwargs': {'extra': 'baz'}, 'param_with_default': 'bars', 'y': 2, 'x': 1}

回答 8

这是无需使用任何模块即可获取功能参数的另一种方法。

def get_parameters(func):
    keys = func.__code__.co_varnames[:func.__code__.co_argcount][::-1]
    sorter = {j: i for i, j in enumerate(keys[::-1])} 
    values = func.__defaults__[::-1]
    kwargs = {i: j for i, j in zip(keys, values)}
    sorted_args = tuple(
        sorted([i for i in keys if i not in kwargs], key=sorter.get)
    )
    sorted_kwargs = {}
    for i in sorted(kwargs.keys(), key=sorter.get):
        sorted_kwargs[i] = kwargs[i]      
    return sorted_args, sorted_kwargs


def f(a, b, c="hello", d="world"): var = a


print(get_parameters(f))

输出:

(('a', 'b'), {'c': 'hello', 'd': 'world'})

Here is another way to get the function parameters without using any module.

def get_parameters(func):
    keys = func.__code__.co_varnames[:func.__code__.co_argcount][::-1]
    sorter = {j: i for i, j in enumerate(keys[::-1])} 
    values = func.__defaults__[::-1]
    kwargs = {i: j for i, j in zip(keys, values)}
    sorted_args = tuple(
        sorted([i for i in keys if i not in kwargs], key=sorter.get)
    )
    sorted_kwargs = {
        i: kwargs[i] for i in sorted(kwargs.keys(), key=sorter.get)
    }   
    return sorted_args, sorted_kwargs


def f(a, b, c="hello", d="world"): var = a
    

print(get_parameters(f))

Output:

(('a', 'b'), {'c': 'hello', 'd': 'world'})

回答 9

返回参数名称列表,负责部分函数和常规函数:

def get_func_args(f):
    if hasattr(f, 'args'):
        return f.args
    else:
        return list(inspect.signature(f).parameters)

Returns a list of argument names, takes care of partials and regular functions:

def get_func_args(f):
    if hasattr(f, 'args'):
        return f.args
    else:
        return list(inspect.signature(f).parameters)

回答 10

更新Brian的答案

如果Python 3中的函数具有仅关键字参数,则需要使用inspect.getfullargspec

def yay(a, b=10, *, c=20, d=30):
    pass
inspect.getfullargspec(yay)

产生这个:

FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=(10,), kwonlyargs=['c', 'd'], kwonlydefaults={'c': 20, 'd': 30}, annotations={})

Update for Brian’s answer:

If a function in Python 3 has keyword-only arguments, then you need to use inspect.getfullargspec:

def yay(a, b=10, *, c=20, d=30):
    pass
inspect.getfullargspec(yay)

yields this:

FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=(10,), kwonlyargs=['c', 'd'], kwonlydefaults={'c': 20, 'd': 30}, annotations={})

回答 11

在python 3中,下面是make *args**kwargsinto dictOrderedDict用于python <3.6维护dict命令):

from functools import wraps

def display_param(func):
    @wraps(func)
    def wrapper(*args, **kwargs):

        param = inspect.signature(func).parameters
        all_param = {
            k: args[n] if n < len(args) else v.default
            for n, (k, v) in enumerate(param.items()) if k != 'kwargs'
        }
        all_param .update(kwargs)
        print(all_param)

        return func(**all_param)
    return wrapper

In python 3, below is to make *args and **kwargs into a dict (use OrderedDict for python < 3.6 to maintain dict orders):

from functools import wraps

def display_param(func):
    @wraps(func)
    def wrapper(*args, **kwargs):

        param = inspect.signature(func).parameters
        all_param = {
            k: args[n] if n < len(args) else v.default
            for n, (k, v) in enumerate(param.items()) if k != 'kwargs'
        }
        all_param .update(kwargs)
        print(all_param)

        return func(**all_param)
    return wrapper

回答 12

inspect.signature非常慢 最快的方法是

def f(a, b=1, *args, c, d=1, **kwargs):
   pass

f_code = f.__code__
f_code.co_varnames[:f_code.co_argcount + f_code.co_kwonlyargcount]  # ('a', 'b', 'c', 'd')

inspect.signature is very slow. Fastest way is

def f(a, b=1, *args, c, d=1, **kwargs):
   pass

f_code = f.__code__
f_code.co_varnames[:f_code.co_argcount + f_code.co_kwonlyargcount]  # ('a', 'b', 'c', 'd')

回答 13

要稍微更新Brian的答案,现在inspect.signature可以在较旧的python版本中使用它的一个很好的反向端口:funcsigs。所以我个人的喜好会

try:  # python 3.3+
    from inspect import signature
except ImportError:
    from funcsigs import signature

def aMethod(arg1, arg2):
    pass

sig = signature(aMethod)
print(sig)

有趣的是,如果您有兴趣玩Signature对象甚至动态创建带有随机签名的函数,您可以看看我的makefun项目。

To update a little bit Brian’s answer, there is now a nice backport of inspect.signature that you can use in older python versions: funcsigs. So my personal preference would go for

try:  # python 3.3+
    from inspect import signature
except ImportError:
    from funcsigs import signature

def aMethod(arg1, arg2):
    pass

sig = signature(aMethod)
print(sig)

For fun, if you’re interested in playing with Signature objects and even creating functions with random signatures dynamically you can have a look at my makefun project.


回答 14

怎么样dir()vars()现在?

似乎完全可以简单地完成被要求的工作……

必须在功能范围内调用。

但请注意,它将返回所有局部变量,因此请确保在函数的开始处进行此操作(如果需要)。

还要注意,正如注释中指出的那样,这不允许在范围之外进行操作。因此,OP的情况不完全相同,但仍与问题标题匹配。因此,我的答案。

What about dir() and vars() now?

Seems doing exactly what is being asked super simply…

Must be called from within the function scope.

But be wary that it will return all local variables so be sure to do it at the very beginning of the function if needed.

Also note that, as pointed out in the comments, this doesn’t allow it to be done from outside the scope. So not exactly OP’s scenario but still matches the question title. Hence my answer.


我如何看待Python对象内部?

问题:我如何看待Python对象内部?

我开始使用Python在各种项目中进行编码(包括Django Web开发和Panda3D游戏开发)。

为了帮助我理解发生了什么,我想基本上在Python对象内部“看”看它们如何打勾-像它们的方法和属性一样。

假设我有一个Python对象,我需要打印出什么内容?那有可能吗?

I’m starting to code in various projects using Python (including Django web development and Panda3D game development).

To help me understand what’s going on, I would like to basically ‘look’ inside the Python objects to see how they tick – like their methods and properties.

So say I have a Python object, what would I need to print out its contents? Is that even possible?


回答 0

Python具有强大的自省功能。

看一下以下内置函数

type()并且dir()是用于检查物体的类型和,分别其属性集的特别有用的。

Python has a strong set of introspection features.

Take a look at the following built-in functions:

type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively.


回答 1

object.__dict__

object.__dict__


回答 2

首先,阅读源代码。

其次,使用dir()功能。

First, read the source.

Second, use the dir() function.


回答 3

我很惊讶没有人提到帮助!

In [1]: def foo():
   ...:     "foo!"
   ...:

In [2]: help(foo)
Help on function foo in module __main__:

foo()
    foo!

帮助可让您阅读文档字符串并了解类可能具有的属性,这非常有帮助。

I’m surprised no one’s mentioned help yet!

In [1]: def foo():
   ...:     "foo!"
   ...:

In [2]: help(foo)
Help on function foo in module __main__:

foo()
    foo!

Help lets you read the docstring and get an idea of what attributes a class might have, which is pretty helpful.


回答 4

如果这是为了探索发生了什么而进行的探索,建议您查看IPython。这添加了各种快捷方式来获取对象文档,属性甚至源代码。例如附加一个“?” 函数将提供对象的帮助(实际上是“ help(obj)”的快捷方式,使用两个?的快捷方式(“ func??”)将显示源代码(如果可用)。

还有很多其他的便利,例如制表符完成,漂亮的结果打印,结果历史记录等,这使得这种探索性编程非常方便。

欲了解更多程序中使用内省的,基本建宏喜欢dir()vars()getattr等将是有益的,但它是值得你花时间检查出的检查模块。要获取函数的来源,请使用“ inspect.getsource”,例如,将其应用于自身:

>>> print inspect.getsource(inspect.getsource)
def getsource(object):
    """Return the text of the source code for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a single string.  An
    IOError is raised if the source code cannot be retrieved."""
    lines, lnum = getsourcelines(object)
    return string.join(lines, '')

inspect.getargspec 如果要处理包装或操纵函数,它通常也很有用,因为它将提供函数参数的名称和默认值。

If this is for exploration to see what’s going on, I’d recommend looking at IPython. This adds various shortcuts to obtain an objects documentation, properties and even source code. For instance appending a “?” to a function will give the help for the object (effectively a shortcut for “help(obj)”, wheras using two ?’s (“func??“) will display the sourcecode if it is available.

There are also a lot of additional conveniences, like tab completion, pretty printing of results, result history etc. that make it very handy for this sort of exploratory programming.

For more programmatic use of introspection, the basic builtins like dir(), vars(), getattr etc will be useful, but it is well worth your time to check out the inspect module. To fetch the source of a function, use “inspect.getsource” eg, applying it to itself:

>>> print inspect.getsource(inspect.getsource)
def getsource(object):
    """Return the text of the source code for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a single string.  An
    IOError is raised if the source code cannot be retrieved."""
    lines, lnum = getsourcelines(object)
    return string.join(lines, '')

inspect.getargspec is also frequently useful if you’re dealing with wrapping or manipulating functions, as it will give the names and default values of function parameters.


回答 5

如果您对此GUI感兴趣,请查看objbrowser。它使用Python标准库中的inspect模块对下面的对象进行自省。

If you’re interested in a GUI for this, take a look at objbrowser. It uses the inspect module from the Python standard library for the object introspection underneath.


回答 6

您可以在外壳程序中使用dir()列出对象的属性:

>>> dir(object())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

当然,还有检查模块:http : //docs.python.org/library/inspect.html#module-inspect

You can list the attributes of a object with dir() in the shell:

>>> dir(object())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Of course, there is also the inspect module: http://docs.python.org/library/inspect.html#module-inspect


回答 7

"""Visit http://diveintopython.net/"""

__author__ = "Mark Pilgrim (mark@diveintopython.org)"


def info(object, spacing=10, collapse=1):
    """Print methods and doc strings.

    Takes module, class, list, dictionary, or string."""
    methodList = [e for e in dir(object) if callable(getattr(object, e))]
    processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
    print "\n".join(["%s %s" %
                     (method.ljust(spacing),
                      processFunc(str(getattr(object, method).__doc__)))
                     for method in methodList])

if __name__ == "__main__":
    print help.__doc__
"""Visit http://diveintopython.net/"""

__author__ = "Mark Pilgrim (mark@diveintopython.org)"


def info(object, spacing=10, collapse=1):
    """Print methods and doc strings.

    Takes module, class, list, dictionary, or string."""
    methodList = [e for e in dir(object) if callable(getattr(object, e))]
    processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
    print "\n".join(["%s %s" %
                     (method.ljust(spacing),
                      processFunc(str(getattr(object, method).__doc__)))
                     for method in methodList])

if __name__ == "__main__":
    print help.__doc__

回答 8

尝试ppretty

from ppretty import ppretty


class A(object):
    s = 5

    def __init__(self):
        self._p = 8

    @property
    def foo(self):
        return range(10)


print ppretty(A(), indent='    ', depth=2, width=30, seq_length=6,
              show_protected=True, show_private=False, show_static=True,
              show_properties=True, show_address=True)

输出:

__main__.A at 0x1debd68L (
    _p = 8, 
    foo = [0, 1, 2, ..., 7, 8, 9], 
    s = 5
)

Try ppretty

from ppretty import ppretty


class A(object):
    s = 5

    def __init__(self):
        self._p = 8

    @property
    def foo(self):
        return range(10)


print ppretty(A(), indent='    ', depth=2, width=30, seq_length=6,
              show_protected=True, show_private=False, show_static=True,
              show_properties=True, show_address=True)

Output:

__main__.A at 0x1debd68L (
    _p = 8, 
    foo = [0, 1, 2, ..., 7, 8, 9], 
    s = 5
)

回答 9

其他人已经提到了dir()内置函数,听起来像您要找的东西,但这是另一个好技巧。许多库(包括大多数标准库)都以源代码形式分发。这意味着您可以轻松地直接阅读源代码。诀窍在于找到它;例如:

>>> import string
>>> string.__file__
'/usr/lib/python2.5/string.pyc'

* .pyc文件已编译,因此请删除结尾的“ c”并在您喜欢的编辑器或文件查看器中打开未编译的* .py文件:

/usr/lib/python2.5/string.py

我发现这对于发现诸如从给定API引发哪些异常之类的事情非常有用。这种细节很少在Python世界中有充分的文献记载。

Others have already mentioned the dir() built-in which sounds like what you’re looking for, but here’s another good tip. Many libraries — including most of the standard library — are distributed in source form. Meaning you can pretty easily read the source code directly. The trick is in finding it; for example:

>>> import string
>>> string.__file__
'/usr/lib/python2.5/string.pyc'

The *.pyc file is compiled, so remove the trailing ‘c’ and open up the uncompiled *.py file in your favorite editor or file viewer:

/usr/lib/python2.5/string.py

I’ve found this incredibly useful for discovering things like which exceptions are raised from a given API. This kind of detail is rarely well-documented in the Python world.


回答 10

尽管pprint其他人已经提到过,但我想添加一些上下文。

pprint模块提供了一种以可以用作解释器输入的形式“漂亮地打印”任意Python数据结构的功能。如果格式化的结构包含不是基本Python类型的对象,则表示可能无法加载。如果包括文件,套接字,类或实例之类的对象,以及许多其他无法用Python常量表示的内置对象,则可能是这种情况。

pprint 寻找PHP替代方案的具有PHP背景的开发人员可能需求很高 var_dump()

带有dict属性的对象可以很好地pprint()与混合使用来转储vars(),它返回__dict__模块,类,实例等的属性:

from pprint import pprint
pprint(vars(your_object))

因此,不需要循环

要转储全局局部作用域中包含的所有变量,只需使用:

pprint(globals())
pprint(locals())

locals()显示函数中定义的变量。
这也是有用的与他们对应的名字作为一个字符串键,其中接入功能的其他用途

locals()['foo']() # foo()
globals()['foo']() # foo()

同样,dir()用于查看模块的内容或对象的属性。

还有更多。

While pprint has been mentioned already by others I’d like to add some context.

The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable. This may be the case if objects such as files, sockets, classes, or instances are included, as well as many other built-in objects which are not representable as Python constants.

pprint might be in high-demand by developers with a PHP background who are looking for an alternative to var_dump().

Objects with a dict attribute can be dumped nicely using pprint() mixed with vars(), which returns the __dict__ attribute for a module, class, instance, etc.:

from pprint import pprint
pprint(vars(your_object))

So, no need for a loop.

To dump all variables contained in the global or local scope simply use:

pprint(globals())
pprint(locals())

locals() shows variables defined in a function.
It’s also useful to access functions with their corresponding name as a string key, among other usages:

locals()['foo']() # foo()
globals()['foo']() # foo()

Similarly, using dir() to see the contents of a module, or the attributes of an object.

And there is still more.


回答 11

正如其他人指出的那样,如果您要查看参数和方法,则可以使用pprintdir()

如果要查看内容的实际值,可以执行

object.__dict__

If you want to look at parameters and methods, as others have pointed out you may well use pprint or dir()

If you want to see the actual value of the contents, you can do

object.__dict__


回答 12

检查代码的两个很棒的工具是:

  1. IPython。允许您使用制表符完成功能进行检查的python终端。

  2. 带有PyDev插件的Eclipse。它具有出色的调试器,可让您在给定的位置中断并通过将所有变量浏览为树来检查对象。您甚至可以使用嵌入式终端在该位置尝试代码或键入对象,然后按“。”。让它为您提供代码提示。

Two great tools for inspecting code are:

  1. IPython. A python terminal that allows you to inspect using tab completion.

  2. Eclipse with the PyDev plugin. It has an excellent debugger that allows you to break at a given spot and inspect objects by browsing all variables as a tree. You can even use the embedded terminal to try code at that spot or type the object and press ‘.’ to have it give code hints for you.


回答 13

pprint和dir一起工作很好

pprint and dir together work great


回答 14

有一个专门用于此目的的python代码库构建:inspect Python 2.7中引入

There is a python code library build just for this purpose: inspect Introduced in Python 2.7


回答 15

如果您希望查看与该对象相对应的函数的源代码,则myobj可以输入iPythonJupyter Notebook

myobj??

If you are interested to see the source code of the function corresponding to the object myobj, you can type in iPython or Jupyter Notebook:

myobj??


回答 16

import pprint

pprint.pprint(obj.__dict__)

要么

pprint.pprint(vars(obj))
import pprint

pprint.pprint(obj.__dict__)

or

pprint.pprint(vars(obj))

回答 17

如果要查看活动对象内部,则python的inspect模块是一个很好的答案。通常,它用于获取在磁盘上某处的源文件中定义的功能的源代码。如果要获取解释器中定义的实时函数和lambda的来源,则可以使用dill.source.getsourcefrom dill。它也可以从咖喱中定义的绑定或未绑定类方法和函数中获取代码。但是,如果没有封闭对象的代码,则可能无法编译该代码。

>>> from dill.source import getsource
>>> 
>>> def add(x,y):
...   return x+y
... 
>>> squared = lambda x:x**2
>>> 
>>> print getsource(add)
def add(x,y):
  return x+y

>>> print getsource(squared)
squared = lambda x:x**2

>>> 
>>> class Foo(object):
...   def bar(self, x):
...     return x*x+x
... 
>>> f = Foo()
>>> 
>>> print getsource(f.bar)
def bar(self, x):
    return x*x+x

>>> 

If you want to look inside a live object, then python’s inspect module is a good answer. In general, it works for getting the source code of functions that are defined in a source file somewhere on disk. If you want to get the source of live functions and lambdas that were defined in the interpreter, you can use dill.source.getsource from dill. It also can get the code for from bound or unbound class methods and functions defined in curries… however, you might not be able to compile that code without the enclosing object’s code.

>>> from dill.source import getsource
>>> 
>>> def add(x,y):
...   return x+y
... 
>>> squared = lambda x:x**2
>>> 
>>> print getsource(add)
def add(x,y):
  return x+y

>>> print getsource(squared)
squared = lambda x:x**2

>>> 
>>> class Foo(object):
...   def bar(self, x):
...     return x*x+x
... 
>>> f = Foo()
>>> 
>>> print getsource(f.bar)
def bar(self, x):
    return x*x+x

>>> 

回答 18

vars(obj)返回对象的属性。

vars(obj) returns the attributes of an object.


回答 19

另外,如果您想查看列表和字典,则可以使用pprint()

In addition if you want to look inside list and dictionaries, you can use pprint()


回答 20

已经有很多好的小费,但是最短和最简单的(不一定是最好的)尚未被提及:

object?

Many good tipps already, but the shortest and easiest (not necessarily the best) has yet to be mentioned:

object?

回答 21

尝试使用:

print(object.stringify())
  • object您要检查的对象的变量名在哪里。

这会打印出格式正确的选项卡式输出,显示对象中所有键和值的层次结构。

注意:这在python3中有效。不知道它是否可以在早期版本中使用

更新:这不适用于所有类型的对象。如果遇到这些类型之一(例如Request对象),请改用以下一种方法:

  • dir(object())

要么

import pprint 然后: pprint.pprint(object.__dict__)

Try using:

print(object.stringify())
  • where object is the variable name of the object you are trying to inspect.

This prints out a nicely formatted and tabbed output showing all the hierarchy of keys and values in the object.

NOTE: This works in python3. Not sure if it works in earlier versions

UPDATE: This doesn’t work on all types of objects. If you encounter one of those types (like a Request object), use one of the following instead:

  • dir(object())

or

import pprint then: pprint.pprint(object.__dict__)


从该函数中确定函数名称(不使用回溯)

问题:从该函数中确定函数名称(不使用回溯)

在Python中,不使用traceback模块,是否有办法从该函数内部确定函数名称?

说我有一个带功能栏的模块foo。执行时foo.bar(),bar是否有办法知道bar的名称?还是更好,foo.bar名字?

#foo.py  
def bar():
    print "my name is", __myname__ # <== how do I calculate this at runtime?

In Python, without using the traceback module, is there a way to determine a function’s name from within that function?

Say I have a module foo with a function bar. When executing foo.bar(), is there a way for bar to know bar’s name? Or better yet, foo.bar‘s name?

#foo.py  
def bar():
    print "my name is", __myname__ # <== how do I calculate this at runtime?

回答 0

Python没有功能来访问函数本身或函数内部的名称。已经提出但遭到拒绝。如果您不想自己玩堆栈,则应该使用"bar"bar.__name__取决于上下文。

给定的拒绝通知是:

该PEP被拒绝。目前尚不清楚在极端情况下应该如何实现它或确切的语义,也没有足够的重要用例。回应充其量是冷淡的。

Python doesn’t have a feature to access the function or its name within the function itself. It has been proposed but rejected. If you don’t want to play with the stack yourself, you should either use "bar" or bar.__name__ depending on context.

The given rejection notice is:

This PEP is rejected. It is not clear how it should be implemented or what the precise semantics should be in edge cases, and there aren’t enough important use cases given. response has been lukewarm at best.


回答 1

import inspect

def foo():
   print(inspect.stack()[0][3])
   print(inspect.stack()[1][3]) #will give the caller of foos name, if something called foo
import inspect

def foo():
   print(inspect.stack()[0][3])
   print(inspect.stack()[1][3]) #will give the caller of foos name, if something called foo

回答 2

有几种方法可以得到相同的结果:

from __future__ import print_function
import sys
import inspect

def what_is_my_name():
    print(inspect.stack()[0][0].f_code.co_name)
    print(inspect.stack()[0][3])
    print(inspect.currentframe().f_code.co_name)
    print(sys._getframe().f_code.co_name)

请注意,inspect.stack呼叫比其他方法慢数千倍:

$ python -m timeit -s 'import inspect, sys' 'inspect.stack()[0][0].f_code.co_name'
1000 loops, best of 3: 499 usec per loop
$ python -m timeit -s 'import inspect, sys' 'inspect.stack()[0][3]'
1000 loops, best of 3: 497 usec per loop
$ python -m timeit -s 'import inspect, sys' 'inspect.currentframe().f_code.co_name'
10000000 loops, best of 3: 0.1 usec per loop
$ python -m timeit -s 'import inspect, sys' 'sys._getframe().f_code.co_name'
10000000 loops, best of 3: 0.135 usec per loop

There are a few ways to get the same result:

from __future__ import print_function
import sys
import inspect

def what_is_my_name():
    print(inspect.stack()[0][0].f_code.co_name)
    print(inspect.stack()[0][3])
    print(inspect.currentframe().f_code.co_name)
    print(sys._getframe().f_code.co_name)

Note that the inspect.stack calls are thousands of times slower than the alternatives:

$ python -m timeit -s 'import inspect, sys' 'inspect.stack()[0][0].f_code.co_name'
1000 loops, best of 3: 499 usec per loop
$ python -m timeit -s 'import inspect, sys' 'inspect.stack()[0][3]'
1000 loops, best of 3: 497 usec per loop
$ python -m timeit -s 'import inspect, sys' 'inspect.currentframe().f_code.co_name'
10000000 loops, best of 3: 0.1 usec per loop
$ python -m timeit -s 'import inspect, sys' 'sys._getframe().f_code.co_name'
10000000 loops, best of 3: 0.135 usec per loop

回答 3

您可以使用@Andreas Jung显示的方法来获得定义的名称,但这可能不是使用该函数调用的名称:

import inspect

def Foo():
   print inspect.stack()[0][3]

Foo2 = Foo

>>> Foo()
Foo

>>> Foo2()
Foo

我不能说这种区别对您是否重要。

You can get the name that it was defined with using the approach that @Andreas Jung shows, but that may not be the name that the function was called with:

import inspect

def Foo():
   print inspect.stack()[0][3]

Foo2 = Foo

>>> Foo()
Foo

>>> Foo2()
Foo

Whether that distinction is important to you or not I can’t say.


回答 4

functionNameAsString = sys._getframe().f_code.co_name

我想要一个非常类似的东西,因为我想将函数名称放在一个日志字符串中,该字符串在我的代码中占据了很多位置。可能不是执行此操作的最佳方法,但是这是一种获取当前函数名称的方法。

functionNameAsString = sys._getframe().f_code.co_name

I wanted a very similar thing because I wanted to put the function name in a log string that went in a number of places in my code. Probably not the best way to do that, but here’s a way to get the name of the current function.


回答 5

我将这个方便的实用程序放在附近:

import inspect
myself = lambda: inspect.stack()[1][3]

用法:

myself()

I keep this handy utility nearby:

import inspect
myself = lambda: inspect.stack()[1][3]

Usage:

myself()

回答 6

我想这inspect是最好的方法。例如:

import inspect
def bar():
    print("My name is", inspect.stack()[0][3])

I guess inspect is the best way to do this. For example:

import inspect
def bar():
    print("My name is", inspect.stack()[0][3])

回答 7

我找到了一个将写函数名称的包装器

from functools import wraps

def tmp_wrap(func):
    @wraps(func)
    def tmp(*args, **kwargs):
        print func.__name__
        return func(*args, **kwargs)
    return tmp

@tmp_wrap
def my_funky_name():
    print "STUB"

my_funky_name()

这将打印

my_funky_name

存根

I found a wrapper that will write the function name

from functools import wraps

def tmp_wrap(func):
    @wraps(func)
    def tmp(*args, **kwargs):
        print func.__name__
        return func(*args, **kwargs)
    return tmp

@tmp_wrap
def my_funky_name():
    print "STUB"

my_funky_name()

This will print

my_funky_name

STUB


回答 8

这实际上是从该问题的其他答案中得出的。

这是我的看法:

import sys

# for current func name, specify 0 or no argument.
# for name of caller of current func, specify 1.
# for name of caller of caller of current func, specify 2. etc.
currentFuncName = lambda n=0: sys._getframe(n + 1).f_code.co_name


def testFunction():
    print "You are in function:", currentFuncName()
    print "This function's caller was:", currentFuncName(1)    


def invokeTest():
    testFunction()


invokeTest()

# end of file

与使用inspect.stack()相比,此版本的可能优势是它应该快数千倍[请参阅Alex Melihoff的文章和有关使用sys._getframe()而不是使用inspect.stack()的时间]。

This is actually derived from the other answers to the question.

Here’s my take:

import sys

# for current func name, specify 0 or no argument.
# for name of caller of current func, specify 1.
# for name of caller of caller of current func, specify 2. etc.
currentFuncName = lambda n=0: sys._getframe(n + 1).f_code.co_name


def testFunction():
    print "You are in function:", currentFuncName()
    print "This function's caller was:", currentFuncName(1)    


def invokeTest():
    testFunction()


invokeTest()

# end of file

The likely advantage of this version over using inspect.stack() is that it should be thousands of times faster [see Alex Melihoff’s post and timings regarding using sys._getframe() versus using inspect.stack() ].


回答 9

print(inspect.stack()[0].function) 似乎也可以使用(Python 3.5)。

print(inspect.stack()[0].function) seems to work too (Python 3.5).


回答 10

这是一种面向未来的方法。

将@CamHart和@Yuval的建议与@RoshOxymoron的可接受答案结合起来,可以避免以下情况:

  • _hidden 和可能不推荐使用的方法
  • 索引到堆栈中(可以在以后的python中重新排序)

因此,我认为这对将来的python版本(在2.7.3和3.3.2中进行测试)非常有用:

from __future__ import print_function
import inspect

def bar():
    print("my name is '{}'".format(inspect.currentframe().f_code.co_name))

Here’s a future-proof approach.

Combining @CamHart’s and @Yuval’s suggestions with @RoshOxymoron’s accepted answer has the benefit of avoiding:

  • _hidden and potentially deprecated methods
  • indexing into the stack (which could be reordered in future pythons)

So I think this plays nice with future python versions (tested on 2.7.3 and 3.3.2):

from __future__ import print_function
import inspect

def bar():
    print("my name is '{}'".format(inspect.currentframe().f_code.co_name))

回答 11

import sys

def func_name():
    """
    :return: name of caller
    """
    return sys._getframe(1).f_code.co_name

class A(object):
    def __init__(self):
        pass
    def test_class_func_name(self):
        print(func_name())

def test_func_name():
    print(func_name())

测试:

a = A()
a.test_class_func_name()
test_func_name()

输出:

test_class_func_name
test_func_name
import sys

def func_name():
    """
    :return: name of caller
    """
    return sys._getframe(1).f_code.co_name

class A(object):
    def __init__(self):
        pass
    def test_class_func_name(self):
        print(func_name())

def test_func_name():
    print(func_name())

Test:

a = A()
a.test_class_func_name()
test_func_name()

Output:

test_class_func_name
test_func_name

回答 12

我不确定为什么人们会变得复杂:

import sys 
print("%s/%s" %(sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name))

I am not sure why people make it complicated:

import sys 
print("%s/%s" %(sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name))

回答 13

import inspect

def whoami():
    return inspect.stack()[1][3]

def whosdaddy():
    return inspect.stack()[2][3]

def foo():
    print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())
    bar()

def bar():
    print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())

foo()
bar()

在IDE中,代码输出

你好,我是foo,爸爸是

你好,我是酒吧,爸爸是foo

你好,我在酒吧,爸爸是

import inspect

def whoami():
    return inspect.stack()[1][3]

def whosdaddy():
    return inspect.stack()[2][3]

def foo():
    print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())
    bar()

def bar():
    print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())

foo()
bar()

In IDE the code outputs

hello, I’m foo, daddy is

hello, I’m bar, daddy is foo

hello, I’m bar, daddy is


回答 14

您可以使用装饰器:

def my_function(name=None):
    return name

def get_function_name(function):
    return function(name=function.__name__)

>>> get_function_name(my_function)
'my_function'

You can use a decorator:

def my_function(name=None):
    return name

def get_function_name(function):
    return function(name=function.__name__)

>>> get_function_name(my_function)
'my_function'

回答 15

我使用自己的方法在多重继承场景中安全地调用super(我把所有代码都放了进去)

def safe_super(_class, _inst):
    """safe super call"""
    try:
        return getattr(super(_class, _inst), _inst.__fname__)
    except:
        return (lambda *x,**kx: None)


def with_name(function):
    def wrap(self, *args, **kwargs):
        self.__fname__ = function.__name__
        return function(self, *args, **kwargs)
return wrap

样本用法:

class A(object):

    def __init__():
        super(A, self).__init__()

    @with_name
    def test(self):
        print 'called from A\n'
        safe_super(A, self)()

class B(object):

    def __init__():
        super(B, self).__init__()

    @with_name
    def test(self):
        print 'called from B\n'
        safe_super(B, self)()

class C(A, B):

    def __init__():
        super(C, self).__init__()

    @with_name
    def test(self):
        print 'called from C\n'
        safe_super(C, self)()

测试它:

a = C()
a.test()

输出:

called from C
called from A
called from B

在每个@with_name装饰方法中,您可以访问self .__ fname__作为当前函数名称。

I do my own approach used for calling super with safety inside multiple inheritance scenario (I put all the code)

def safe_super(_class, _inst):
    """safe super call"""
    try:
        return getattr(super(_class, _inst), _inst.__fname__)
    except:
        return (lambda *x,**kx: None)


def with_name(function):
    def wrap(self, *args, **kwargs):
        self.__fname__ = function.__name__
        return function(self, *args, **kwargs)
return wrap

sample usage:

class A(object):

    def __init__():
        super(A, self).__init__()

    @with_name
    def test(self):
        print 'called from A\n'
        safe_super(A, self)()

class B(object):

    def __init__():
        super(B, self).__init__()

    @with_name
    def test(self):
        print 'called from B\n'
        safe_super(B, self)()

class C(A, B):

    def __init__():
        super(C, self).__init__()

    @with_name
    def test(self):
        print 'called from C\n'
        safe_super(C, self)()

testing it :

a = C()
a.test()

output:

called from C
called from A
called from B

Inside each @with_name decorated method you have access to self.__fname__ as the current function name.


回答 16

我最近尝试使用以上答案从该函数的上下文访问该函数的文档字符串,但由于上述问题仅返回了名称字符串,因此它不起作用。

幸运的是,我找到了一个简单的解决方案。如果像我一样,您要引用该函数,而不是简单地获取表示名称的字符串,您可以将eval()应用于函数名称的字符串。

import sys
def foo():
    """foo docstring"""
    print(eval(sys._getframe().f_code.co_name).__doc__)

I recently tried to use the above answers to access the docstring of a function from the context of that function but as the above questions were only returning the name string it did not work.

Fortunately I found a simple solution. If like me, you want to refer to the function rather than simply get the string representing the name you can apply eval() to the string of the function name.

import sys
def foo():
    """foo docstring"""
    print(eval(sys._getframe().f_code.co_name).__doc__)

回答 17

我建议不要依赖堆栈元素。如果有人在不同的上下文(例如python解释器)中使用您的代码,则您的堆栈将更改并破坏索引([0] [3])。

我建议你这样:

class MyClass:

    def __init__(self):
        self.function_name = None

    def _Handler(self, **kwargs):
        print('Calling function {} with parameters {}'.format(self.function_name, kwargs))
        self.function_name = None

    def __getattr__(self, attr):
        self.function_name = attr
        return self._Handler


mc = MyClass()
mc.test(FirstParam='my', SecondParam='test')
mc.foobar(OtherParam='foobar')

I suggest not to rely on stack elements. If someone use your code within different contexts (python interpreter for instance) your stack will change and break your index ([0][3]).

I suggest you something like that:

class MyClass:

    def __init__(self):
        self.function_name = None

    def _Handler(self, **kwargs):
        print('Calling function {} with parameters {}'.format(self.function_name, kwargs))
        self.function_name = None

    def __getattr__(self, attr):
        self.function_name = attr
        return self._Handler


mc = MyClass()
mc.test(FirstParam='my', SecondParam='test')
mc.foobar(OtherParam='foobar')

回答 18

用装饰器很容易做到这一点。

>>> from functools import wraps

>>> def named(func):
...     @wraps(func)
...     def _(*args, **kwargs):
...         return func(func.__name__, *args, **kwargs)
...     return _
... 

>>> @named
... def my_func(name, something_else):
...     return name, something_else
... 

>>> my_func('hello, world')
('my_func', 'hello, world')

This is pretty easy to accomplish with a decorator.

>>> from functools import wraps

>>> def named(func):
...     @wraps(func)
...     def _(*args, **kwargs):
...         return func(func.__name__, *args, **kwargs)
...     return _
... 

>>> @named
... def my_func(name, something_else):
...     return name, something_else
... 

>>> my_func('hello, world')
('my_func', 'hello, world')