When is del useful in python?

前端 未结 21 1844
野趣味
野趣味 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:22

    del is often seen in __init__.py files. Any global variable that is defined in an __init__.py file is automatically "exported" (it will be included in a from module import *). One way to avoid this is to define __all__, but this can get messy and not everyone uses it.

    For example, if you had code in __init__.py like

    import sys
    if sys.version_info < (3,):
        print("Python 2 not supported")
    

    Then your module would export the sys name. You should instead write

    import sys
    if sys.version_info < (3,):
        print("Python 2 not supported")
    
    del sys
    

提交回复
热议问题