Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dir builtins not consistent

I would like to check programmatically if print is a built-in Python funcion.

Using Python 3.4.x when querying dir(__builtins__) from the Python command line I get what I'm looking for:

['ArithmeticError', 'AssertionError', ..... , 'pow', 'print' ... ]

But when using it in a .py file:

import sys

def foo:
   print(dir(__builtins__))

The call returns:

 ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
 '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
 '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
 '__len__', '__lt__', '__ne__', '__new__', '__reduce__',
 '__reduce_ex__', '__repr__', '__setattr__', '__setitem__',
 '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy',
 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault',
 'update', 'values']

I haven't redefined __builtins__ at any point.

like image 593
Willeman Avatar asked Mar 17 '26 11:03

Willeman


1 Answers

Quoting the builtins module documentation:

As an implementation detail, most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this module’s __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.

In the command prompt, you are looking at the module object, vs. the __dict__ object when running the code in a python file. The dir() of a dictionary is rather different from dir() on a module object.

Rather than look at __builtins__, use the builtins module:

import builtins

hasattr(builtins, 'print')
like image 185
Martijn Pieters Avatar answered Mar 18 '26 23:03

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!