6

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Is it because it can mislead users to think it is a standard defined name? Or is it because it's meant to be future-proof, as anytime a variable with that name can be implemented in the standard library? There are cases when exactly this is intended and emphasized with these names, that something "magic" occurs.
User defined __ are a private marker. Since python is interpreted, there is not realy private var/method. Use only one underscore to mark your vars as "be careful".The acces of __vars is slower than usual, so you have no reason to use this.
What backs the interpretation that a programmer should not invent such a name? My problem is, programmers are writing apis for programmers here. Which one is the "your own" programmer?
taken the question to be at stackoverflow.com/questions/27965088/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.