Skip to content

Instantly share code, notes, and snippets.

@ishikawa
Created July 26, 2008 03:11
Show Gist options
  • Select an option

  • Save ishikawa/2592 to your computer and use it in GitHub Desktop.

Select an option

Save ishikawa/2592 to your computer and use it in GitHub Desktop.
Name Mangling Of Python Private Variables
def _mangle_name(self, name):
"""
Any identifier of the form __spam (at least two leading underscores,
at most one trailing underscore) is textually replaced with
_classname__spam, where classname is the current class name with
leading underscore(s) stripped.
Truncation may occur when the mangled name would be longer than
255 characters. When the class name consists of only underscores,
no mangling occurs.
"""
klass = self.__class__.__name__
if name.startswith("__") and not name.endswith("__"):
import re
if not re.compile(r"^_+$").match(klass):
# NOTE: In Python 2.5, no trunction occurred?
#name = ("_%s%s" % (klass, name))[0:255]
name = ("_%s%s" % (klass, name))
return name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment