How recommended is using custom double underscore variables in Python?

大城市里の小女人 提交于 2020-01-01 05:32:07

问题


I was wondering, is it recommended/Pythonic to define and use custom double underscore variables/functions in a Python script? For example, __tablename__ as used in SQLAlchemy or __validateitem__() (a custom function that validates an item before applying __setitem__() to it).

If it does define that something magic happens, or that that specific variable/function is used indeed in a special way (like the two above examples), I feel it is a good idea using them.

I am interested in arguments on both best coding practices and potential risks in using this kind of naming.


回答1:


From PEP8:

__double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

So, the advice is not to use the double underscore syntax for your own variables.



来源:https://stackoverflow.com/questions/21587882/how-recommended-is-using-custom-double-underscore-variables-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!