RAII in Python - automatic destruction when leaving a scope

前端 未结 5 1135
我寻月下人不归
我寻月下人不归 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 05:02

    1. You are right about with -- it is completely unrelated to variable scoping.

    2. Avoid global variables if you think they are a problem. This includes module level variables.

    3. The main tool to hide state in Python are classes.

    4. Generator expressions (and in Python 3 also list comprehensions) have their own scope.

    5. If your functions are long enough for you to lose track of the local variables, you should probably refactor your code.

提交回复
热议问题