This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: getattr() returns None even when default is given
Type: Stage: resolved
Components: Versions: Python 2.7
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: darkdragon-001, steven.daprano
Priority: normal Keywords:

Created on 2017-11-29 02:18 by darkdragon-001, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg307197 - (view) Author: (darkdragon-001) Date: 2017-11-29 02:18
def main():
    patch = './a'
    f = open(patch, 'r')
    a = getattr(f,'encoding','ascii')

if __name__ == "__main__":


$ touch a
$ python

It still prints out 'None' instead of 'ascii'. This issue is fixed in python3.
msg307198 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2017-11-29 02:24
That's not a bug. That's because the file object does have an encoding attribute, which is set to None.

getattr only returns the default when the attribute doesn't exist, not if it exists but is None.
Date User Action Args
2022-04-11 14:58:54adminsetgithub: 76344
2017-11-29 16:51:28rhettingersetstatus: open -> closed
2017-11-29 02:24:46steven.dapranosetnosy: + steven.daprano
messages: + msg307198

resolution: not a bug
stage: resolved
2017-11-29 02:18:28darkdragon-001create