7

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.

4
  • Maybe a good better idea should be to ask to project's developers why the hell they do this! Mar 27, 2015 at 17:26
  • 1
    Having those names in the module namespace will 1. be very slightly more performant than accessing them in as built-ins, and 2. not be affected by any later-imported modules' redefinitions of built-ins. Why they did it, I can't say; people just liked it better that way...
    – kindall
    Mar 27, 2015 at 17:27
  • Which case you need performance importing builtins methods? And, this approach does not works on Python 2.x Mar 27, 2015 at 17:46
  • 3
    @MauroBaraldi - On 2.x, builtins comes from pip install futures. There isn't a native builtins module.
    – tdelaney
    Mar 27, 2015 at 18:01

1 Answer 1

13

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.

1
  • 3
    Note builtins is part of the future pypi package (i.e. it can be installed via pip install future)
    – Tom Close
    Mar 13, 2016 at 23:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.