Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why import builtins if you never redefine any built-in functions?

I am looking at the code in this repo https://github.com/datacenter/cobra and I am seeing imports from builtins as follows in a few files:

cobra/internal/codec/jsoncodec.py:15:from builtins import str
cobra/internal/codec/xmlcodec.py:15:from builtins import str
cobra/internal/base/moimpl.py:16:from builtins import next
cobra/internal/base/moimpl.py:17:from builtins import str
cobra/internal/base/moimpl.py:18:from builtins import object
cobra/internal/rest/accessimpl.py:15:from builtins import object
cobra/internal/rest/accessimpl.py:16:from builtins import str
cobra/mit/session.py:15:from builtins import str
cobra/mit/session.py:16:from builtins import object
cobra/mit/meta.py:16:from builtins import str
cobra/mit/meta.py:17:from builtins import next
cobra/mit/meta.py:18:from builtins import object
cobra/mit/access.py:21:from builtins import object
cobra/mit/naming.py:15:from builtins import next
cobra/mit/naming.py:16:from builtins import str
cobra/mit/naming.py:17:from builtins import object
cobra/mit/request.py:15:from builtins import str
cobra/mit/request.py:16:from builtins import object

What is the logic/what is gained by doing this? There is no place in the module where these objects are re-defined.

On a side note, this breaks the 2.7 compatibility I was expecting from this module as specified in the docs.

like image 327
Fred Thomsen Avatar asked Mar 27 '15 17:03

Fred Thomsen


People also ask

What does Builtins mean in Python?

The builtins module is automatically loaded every time Python interpreter starts, either as a top level execution environment or as interactive session. The Object class, which happens to be the base class for all Python objects, is defined in this module.

What is Builtins module?

This module provides direct access to all 'built-in' identifiers of Python; for example, builtins. open is the full name for the built-in function open() . See Built-in Functions and Built-in Constants for documentation.

Which of the following statements Retreives all builtin objects in Python?

Check with the built-in function dir() You can get a list of names of built-in objects, such as built-in functions and constants, by passing the builtins module or __builtins__ to dir() . To make the output easier to read, use pprint.


1 Answers

I don't know why its done in cobra specifically, but its a trick for writing code that works in python 2 and 3. See compatible_idioms. It shouldn't break 2.7 but you have to write "3x-ish" code.

update

For 2.x, the builtins module needs to be installed from pypi. Its not the native builtin functions, but 3.x compatible updates.

like image 161
tdelaney Avatar answered Oct 31 '22 00:10

tdelaney