Posted By

ishikawa on 06/30/08


Tagged

python


Versions (?)

Name Mangling of Python Private Variables


 / Published in: Python
 

Python: Private Variables http://docs.python.org/tut/node11.html#SECTION0011600000000000000000

Any identifier of the form spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classnamespam, 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.

  1. def _mangle_name(self, name):
  2. """
  3. Any identifier of the form __spam (at least two leading underscores,
  4. at most one trailing underscore) is textually replaced with
  5. _classname__spam, where classname is the current class name with
  6. leading underscore(s) stripped.
  7.  
  8. Truncation may occur when the mangled name would be longer than
  9. 255 characters. When the class name consists of only underscores,
  10. no mangling occurs.
  11. """
  12.  
  13. klass = self.__class__.__name__
  14. if name.startswith("__") and not name.endswith("__"):
  15. import re
  16. if not re.compile(r"^_+$").match(klass):
  17. # NOTE: In Python 2.5, no trunction occurred?
  18. #name = ("_%s%s" % (klass, name))[0:255]
  19. name = ("_%s%s" % (klass, name))
  20. return name

Report this snippet  

You need to login to post a comment.