Home > OS >  Why getattr is throwing 'module' object is not callable Error
Why getattr is throwing 'module' object is not callable Error

Time:07-08

Why I am getting error 'module' object is not callable here

import platform

mm = ['architecture', 'collections', 'java_ver', 'libc_ver', 'mac_ver', 'machine', 'node', 'os', 'platform', 'processor', 'python_branch', 'python_build', 'python_compiler', 'python_implementation',
      'python_revision', 'python_version', 'python_version_tuple', 're', 'release', 'sys', 'system', 'system_alias', 'uname', 'uname_result', 'version', 'win32_edition', 'win32_is_iot', 'win32_ver']


for i in mm:
    c = getattr(platform,i)()
    print(c)

I am trying to call output like platform.archirecture() so have added parentheses

CodePudding user response:

You can use the try-except block to prevent this error.


import platform

mm = ['architecture', 'collections', 'java_ver', 'libc_ver', 'mac_ver', 'machine', 'node', 'os', 'platform', 'processor', 'python_branch', 'python_build', 'python_compiler', 'python_implementation',
      'python_revision', 'python_version', 'python_version_tuple', 're', 'release', 'sys', 'system', 'system_alias', 'uname', 'uname_result', 'version', 'win32_edition', 'win32_is_iot', 'win32_ver']


for i in mm:
    try:
        c = getattr(platform,i)()
    except TypeError:
        c = getattr(platform,i)
    print(c)

CodePudding user response:

Something like this – only call the callable members.

I removed some entries from the list since they weren't relevant, or can't be called without arguments.

import platform

mm = [
    "architecture",
    "collections",
    "java_ver",
    "libc_ver",
    "mac_ver",
    "machine",
    "node",
    "os",
    "platform",
    "processor",
    "python_branch",
    "python_build",
    "python_compiler",
    "python_implementation",
    "python_revision",
    "python_version",
    "python_version_tuple",
    "release",
    "system",
    "uname",
    "version",
    "win32_edition",
    "win32_is_iot",
    "win32_ver",
]

for name in mm:
    attr = getattr(platform, name, None)
    if not attr:
        continue
    if callable(attr):
        attr = attr()
    print(name, attr)

CodePudding user response:

it also can be when you call the module object meaning the module's object have the same name as the module so try renaming at c = getattr(platform, ...) change platform bc its the same name as the module. :)

  • Related