What does locals()['_[1]'] mean in Python?

后端 未结 4 601
一向
一向 2021-01-11 12:04

I saw a one liner code that is claimed to remove duplicates from a sequence:

u = [x for x in seq if x not in locals()[\'_[1]\']]

I tried th

4条回答
  •  清歌不尽
    2021-01-11 12:46

    It is a temporary name used in a list comprehension by Python 2.6 and earlier. Python 2.7 and Python 3.x fixed this wart: the list being created is no longer accessible until creation has finished.

    Or in short it was an implementation detail that nobody should ever have relied on.

    Here you can see that Python 2.7 leaves locals() unchanged while Python 2.6 creates a short live temporary:

    Python 2.7.2 (default, Jan  5 2012, 16:24:09)
    [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> def foo():
            t = [list(locals().keys()) for x in range(1) ]
            print(locals())
            print(t[0])
    
    >>> foo()
    {'x': 0, 't': [['x']]}
    ['x']
    >>>
    
    Python 2.6.7 (r267:88850, Jan  5 2012, 16:18:48)
    [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> def foo():
            t = [list(locals().keys()) for x in range(1) ]
            print(locals())
            print(t[0])
    
    >>> foo()
    {'x': 0, 't': [['_[1]', 'x']]}
    ['_[1]', 'x']
    >>>
    

    Python 3.x introduces a new short lived temporary for list comprehensions called .0. Don't be tempted to use that for anything either. Also the whole list comprehension runs in a separate namespace so the loop variables aren't accessible outside the loop either:

    Python 3.2 (r32:88445, Jan  5 2012, 16:29:57)
    [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> def foo():
            t = [list(locals().keys()) for x in range(1) ]
            print(locals())
            print(t[0])
    
    >>> foo()
    {'t': [['.0', 'x']]}
    ['.0', 'x']
    

提交回复
热议问题