When is del useful in python?

前端 未结 21 2258
野趣味
野趣味 2020-11-22 11:58

I can\'t really think of any reason why python needs the del keyword (and most languages seem to not have a similar keyword). For instance, rather than deletin

21条回答
  •  故里飘歌
    2020-11-22 12:35

    As an example of what del can be used for, I find it useful i situations like this:

    def f(a, b, c=3):
        return '{} {} {}'.format(a, b, c)
    
    def g(**kwargs):
        if 'c' in kwargs and kwargs['c'] is None:
            del kwargs['c']
    
        return f(**kwargs)
    
    # g(a=1, b=2, c=None) === '1 2 3'
    # g(a=1, b=2) === '1 2 3'
    # g(a=1, b=2, c=4) === '1 2 4'
    

    These two functions can be in different packages/modules and the programmer doesn't need to know what default value argument c in f actually have. So by using kwargs in combination with del you can say "I want the default value on c" by setting it to None (or in this case also leave it).

    You could do the same thing with something like:

    def g(a, b, c=None):
        kwargs = {'a': a,
                  'b': b}
        if c is not None:
            kwargs['c'] = c
    
        return f(**kwargs)
    

    However I find the previous example more DRY and elegant.

提交回复
热议问题