Python如何区分内建函数中显式传递的None作为参数

Iva*_*hko 3 python built-in python-internals

我尝试了下一个代码:

>>> f = object()

# It's obvious behavior:
>>> f.foo
Traceback (most recent call last):       
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'

# However, the next one is surprising me!
>>> getattr(f, 'foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'

# And this one returns None as expected:
>>> getattr(f, 'foo', None)
Run Code Online (Sandbox Code Playgroud)

然后我getattr()在PyCharm IDE中找到了这个伪签名:

def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass
Run Code Online (Sandbox Code Playgroud)

我的问题是python如何在内部区分这两种使用getattr()(可能还有其他功能)的方案?是否有可能在客户端代码中完全执行类似的操作?

ig0*_*774 5

正如@scytale所说,的伪签名getattr与其实现不完全对应。我见过尝试在纯Python中复制行为的尝试,如下所示:

class MyObject(object):
    __marker = object()

    def getvalue(key, default=__marker):
        ...
        if key is __marker:
             # no value supplied for default
             ....
Run Code Online (Sandbox Code Playgroud)

换句话说,使用呼叫者无法轻易提供的标记值来检查是否没有提供默认值而不是None