RAII in Python - automatic destruction when leaving a scope

前端 未结 5 1125
我寻月下人不归
我寻月下人不归 2020-12-01 04:29

I\'ve been trying to find RAII in Python. Resource Allocation Is Initialization is a pattern in C++ whereby an object is initialized as it is created. If it fails, then it t

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 04:56

    But RAII also works with the scoping rules of C++ to ensure the prompt destruction of the object.

    This is considered unimportant in GC languages, which are based on the idea that memory is fungible. There is no pressing need to reclaim an object's memory as long as there's enough memory elsewhere to allocate new objects. Non-fungible resources like file handles, sockets, and mutexes are considered a special case to be dealt with specially (e.g., with). This contrasts with C++'s model that treats all resources the same.

    As soon as the variable pops off the stack it is destroyed.

    Python doesn't have stack variables. In C++ terms, everything is a shared_ptr.

    Python does some scoping, but not at the indentation level, just at the functional level. It seems silly to require that I make a new function just to scope the variables so I can reuse a name.

    It also does scoping at the generator comprehension level (and in 3.x, in all comprehensions).

    If you don't want to clobber your for loop variables, don't use so many for loops. In particular, it's un-Pythonic to use append in a loop. Instead of:

    new_points = []
    for x,y,z in surface.points:
        ...     # Do something with the points
        new_points.append( (x,y,z) )
    

    write:

    new_points = [do_something_with(x, y, z) for (x, y, z) in surface.points]
    

    or

    # Can be used in Python 2.4-2.7 to reduce scope of variables.
    new_points = list(do_something_with(x, y, z) for (x, y, z) in surface.points)
    

提交回复
热议问题