Search code examples
pythonimportsetnotation

Use Python 3-styled sets in Python 2


In Python 3, set-notation more closely matches the way sets are represented in set-theory while Python 2 uses a list style (i.e. set_py3 = {"A","B","C"} \ set_py2 = set(["A","B","C"]))

Is there any way to port the set-notation from Python 3 to Python 2 using from __future__?

Py2.7 let's one use the {"A","B","C"} set-notation but when it's printed, it is still set(["A","B","C"]) . I saw the from __future__ import braces but I don't think that introduces this type of set-notation. I know you can import the new print function with from __future__ import print_function. I wasn't sure if there was a similar method for porting set-notation.


Solution

  • There were some features ported to Python 2.7 from 3.1, which include the set expression syntax; and other things:

    Much as Python 2.6 incorporated features from Python 3.0, version 2.7 incorporates some of the new features in Python 3.1. The 2.x series continues to provide tools for migrating to the 3.x series.

    A partial list of 3.1 features that were backported to 2.7:

    • The syntax for set literals ({1,2,3} is a mutable set).
    • Dictionary and set comprehensions ({i: i*2 for i in range(3)}).
    • Multiple context managers in a single with statement.
    • A new version of the io library, rewritten in C for performance.
    • The ordered-dictionary type described in PEP 372: Adding an Ordered Dictionary to collections.
    • The new "," format specifier described in PEP 378: Format Specifier for Thousands Separator.
    • The memoryview object.
    • ...

    So, to use the new syntax, simply upgrade to Python 2.7