Can literals in Python be overridden?

前端 未结 1 992
清歌不尽
清歌不尽 2020-11-30 10:14

Couldn\'t find a way to phrase the title better, feel free to correct.

I\'m pretty new to Python, currently experimenting with the language.. I\'ve noticed that all

相关标签:
1条回答
  • 2020-11-30 10:25

    This is a conscientious choice from Python.

    Firstly, with regards to patching inbuilt type, this is primarily a design decision and only secondarily an optimization. I have learnt from much lurking on the Python Mailing List that monkey patching on builtin types, although enjoyable for small scripts, serves no good purpose in anything larger.

    Libraries, for one, make certain assumptions about types. If it were encouraged to extend default types, many libraries would end up fighting each other. It would also discourage making new types – a deque is a deque, an ordered set is an ordered set, a dictionary is a dictionary and that should be that.

    Literal syntax is a particularly important point. If you cannot guarantee that [1, 2, 3] is a list, what can you guarantee? If people could change those behaviours it would have such global impacts as to destroy the stability of a lot of code. There is a reason goto and global variables are discouraged.


    There is one particular hack that I am fond of, though. When you see r"hello", this seems to be an extended literal form.

    So why not r[1, 2, 3]?

    class ListPrefixer:
        def __init__(self, typ):
            self.typ = typ
    
        def __getitem__(self, args):
            return self.typ(args)
    
    class MyList(list):
        def each(self, func):
            return MyList(func(x) for x in self)
    
    e = ListPrefixer(MyList)
    
    e[1, 2, 3, 4].each(lambda x: x**2)
    #>>> [1, 4, 9, 16]
    

    Finally, if you really want to do deep AST hacks, check out MacroPy.

    0 讨论(0)
提交回复
热议问题