Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does underscoring methods connote?

I am relatively new to the Python language and encountered this in doing the following:

help(list)

Here is what I encountered:

__add__(...)
|      x.__add__(y) <==> x+y
|  
|  __contains__(...)
|      x.__contains__(y) <==> y in x
|  
|  __delitem__(...)
|      x.__delitem__(y) <==> del x[y]

Regarding these, what are the underscores for? Because they aren't used (to my knowledge) when you use a method normally, I'm struggling to understand why they'd take the time to write them out with underscores in the documentation.

like image 500
user386156 Avatar asked Feb 16 '11 13:02

user386156


1 Answers

See the Python style guide for a comprehensive explanation.

In practice:

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, __boo becomes _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.
like image 62
Don Avatar answered Sep 23 '22 09:09

Don