Why do some functions have underscores "__" before and after the function name?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3
--
Chapters
00:00 Question
00:32 Accepted answer (Score 741)
02:09 Answer 2 (Score 81)
02:48 Answer 3 (Score 31)
03:06 Answer 4 (Score 7)
03:53 Thank you
--
Full question
https://stackoverflow.com/questions/8689...
Accepted answer links:
[Python PEP 8 -- Style Guide for Python Code]: https://www.python.org/dev/peps/pep-0008/
[Descriptive: Naming Styles]: https://www.python.org/dev/peps/pep-0008...
Answer 3 links:
[Python Language Reference, section 3, "Data model"]: https://docs.python.org/3/reference/data...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #function #methods #doubleunderscore
#avk47
ACCEPTED ANSWER
Score 809
From the Python PEP 8 -- Style Guide for Python Code:
Descriptive: Naming Styles
The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):
_single_leading_underscore: weak "internal use" indicator. E.g.from M import *does not import objects whose name starts with an underscore.
single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar,__boobecomes_FooBar__boo; see below).
__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.
Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".
ANSWER 2
Score 89
The other respondents are correct in describing the double leading and trailing underscores as a naming convention for "special" or "magic" methods.
While you can call these methods directly ([10, 20].__len__() for example), the presence of the underscores is a hint that these methods are intended to be invoked indirectly (len([10, 20]) for example). Most python operators have an associated "magic" method (for example, a[x] is the usual way of invoking a.__getitem__(x)).
ANSWER 3
Score 34
Names surrounded by double underscores are "special" to Python. They're listed in the Python Language Reference, section 3, "Data model".
ANSWER 4
Score 7
Actually I use _ method names when I need to differ between parent and child class names. I've read some codes that used this way of creating parent-child classes. As an example I can provide this code:
class ThreadableMixin:
def start_worker(self):
threading.Thread(target=self.worker).start()
def worker(self):
try:
self._worker()
except tornado.web.HTTPError, e:
self.set_status(e.status_code)
except:
logging.error("_worker problem", exc_info=True)
self.set_status(500)
tornado.ioloop.IOLoop.instance().add_callback(self.async_callback(self.results))
...
and the child that have a _worker method
class Handler(tornado.web.RequestHandler, ThreadableMixin):
def _worker(self):
self.res = self.render_string("template.html",
title = _("Title"),
data = self.application.db.query("select ... where object_id=%s", self.object_id)
)
...