Search code examples
pythonpython-2.7getattrbuilt-in

Error when trying to get object type in python


I have a main script, which imports another python library that I've been writing. The library contains the following command:

print getattr(__builtins__, "list")

This produces the following error when I call it from the library:

'dict' object has no attribute 'list'

But, if I copy and paste that same command into the main script it works fine. Any ideas why this isn't working?

The header of my main file looks like this:

#/usr/bin/env python
from sys import argv
import re, sys, os, argparse
sys.path.extend(map(os.path.abspath, ['C:/Users/xxxx/scripts/modules/']))
import general

The header for my "general" library is:

#!/usr/bin/env python
from sys import argv
import re, sys, os, argparse

def getBuiltin(name):
    ##Convert a string into an attribute
    try:
        return getattr(__builtins__, name)
    except Exception as e:
        print "Unhandled type in function \"get_builtin\""
        print name
        print e
        exit()

I was calling the library like this:

print general.getBuiltin("list")

where, "getBuiltin" is the name of my function


Solution

  • You can also check this question: Python: What's the difference between __builtin__ and __builtins__?

    As you can see in akent answer, builtins is different in main module and another module:

    Straight from the python documentation: http://docs.python.org/reference/executionmodel.html

    By default, when in the main module, builtins is the built-in module builtin (note: no 's'); when in any other module, builtins is an alias for the dictionary of the builtin module itself.

    builtins can be set to a user-created dictionary to create a weak form of restricted execution.

    CPython implementation detail: Users should not touch builtins; it is strictly an implementation detail. Users wanting to override values in the builtins namespace should import the builtin (no 's') module and modify its attributes appropriately. The namespace for a module is automatically created the first time a module is imported. Note that in Python3, the module builtin has been renamed to builtins to avoid some of this confusion.