True C++-style private attributes for Python, enforced at the C level.
A C++ extension module (private_attribute) that lets you declare attributes
that are only accessible from inside the class that owns them — genuinely
hidden from the outside world, from subclasses, and from hasattr(), dir(),
and obj.__dict__. Unlike Python's name-mangling (_Class__name) and the
leading-underscore convention, these attributes cannot be reached at all from
outside the declaring class's own code.
Python gives you a convention (_private) and a name-mangling trick
(__name → _ClassName__name), but neither is an actual access barrier. Any
code that knows (or can guess) the mangled name can still read and mutate your
"private" state.
private_attribute implements the real thing in C++:
Private attributes are not stored in __dict__.
They are unreachable from outside the class that declares them — including
from subclasses and from getattr/hasattr/dir.
Inside the declaring class, they look and behave like ordinary attributes.
It does this by installing C-struct descriptors for __getattribute__ /
__getattr__ / __setattr__ / __delattr__ / __del__ (and __call__ on
registered metaclasses) and storing private values under generated,
collision-resistant names (a tuple of two SHA-256 hashes).
Installation
pip install private-attribute-cpp
Prebuilt wheels are published for CPython 3.10–3.15 (including free-threaded
t builds) across Linux, macOS, and Windows.
Private attributes may be set on instancesor on the class itself
(class-level private state, e.g. for @classmethod).
They also cover private methods: declare a method name in
__private_attrs__ and it becomes callable only from the class's own code.
They work alongside __slots__ (see notes below).
Custom name generation (private_func)
By default private values are stored under generated hash names. You can
control how the storage name is derived with a private_func callable, which
receives the object id and the attribute name:
private_func may be passed either as a keyword in the class definition (shown
above) or on PrivateAttrBase itself. It is optional; the default generates a
tuple of two SHA-256 hashes.
Decorated methods (PrivateWrapProxy)
Decorators that return a plain wrapper object (anything other than
property / classmethod / staticmethod) would normally break private
attribute access, because the wrapper's bytecode is not recognized as
belonging to the class. PrivateWrapProxy makes arbitrary decorators
compatible:
PrivateWrapProxy(decorator) returns a _PrivateWrap object that wraps the
decorator application. It exposes two public attributes:
.result — the final decorated result.
.funcs — a read-only list proxy (_listproxy) of the original (pre-decoration) functions.
To stack decorators, resolve name conflicts, or fix decorator ordering, chain
.result.<attr> onto the wrapped method and pass the method itself as the
second argument (which saves the previous functions):
The _PrivateWrap object is transparent in normal use: it forwards
__getattr__, __call__, and descriptor __get__ to its .result, so callers
interact with the wrapped method as usual.
Inheritance and use_parents
Since v2.1.0, a subclass's code cannot access its parent's private
attributes — a parent's private attribute is reachable only from the parent's
own code, or from a class that re-declares the same name in its own
__private_attrs__. When a subclass re-declares the same name, the two are
stored separately (instance attributes per declaring class, class-level
attributes per class).
Since v2.2.0, you can opt in to inheriting all ancestors' private names with
use_parents=True:
class Parent(PrivateAttrBase):
__private_attrs__ = ["_secret"]
def __init__(self):
self._secret = 1
def get_secret(self):
return self._secret
class Child(Parent, use_parents=True):
__private_attrs__ = []
def __init__(self):
super().__init__()
self._secret = 99 # stored in Child's own storage
def read_own(self):
return self._secret
obj = Child()
obj.get_secret() # 1 — parent code sees the parent's value
obj.read_own() # 99 — child code sees its own value
The merged names live in the subclass's own storage — they never overwrite
the parent's values. The Python-level __private_attrs__ tuple is left
unchanged; only the internal name set is merged. Default is False.
Cross-class access (PrivateSuper, PrivateClassSuper, and PrivateObjSuper)
Ordinary subclass code cannot see a parent's private attributes. Two explicit
helpers cover the two places those values live:
Class-level storage — PrivateSuper and PrivateClassSuper (since v3.0.0).
Per-instance storage — PrivateObjSuper.
Class-level (PrivateSuper and PrivateClassSuper)
PrivateSuper (instance flavour) and PrivateClassSuper (@classmethod
flavour) reach a parent class's class-level private attribute, including the
value it stored "for" an intermediate class:
B — a parent type of A whose class-level private attribute is accessed.
C — the class the private value was defined for; it must be B, A, or a
class that is both a subclass of B and a parent of A.
the final argument is an instance of A (for PrivateSuper) or a subclass of
A (for PrivateClassSuper).
The attribute is resolved from B's class-level storage for C and its
__get__(obj, A) (or __get__(None, cls)) is invoked. This pair is for
class-level private attributes only.
Per-instance (PrivateObjSuper)
PrivateObjSuper reads the value a parent class stored on a particular
instance. It does not look at class attributes, and it cannot assign or delete.
import private_attribute
class Parent(private_attribute.PrivateAttrBase):
__private_attrs__ = ["_secret"]
def __init__(self):
self._secret = 1
def get_secret(self):
return self._secret
class Child(Parent):
__private_attrs__ = ["_secret"]
def __init__(self):
super().__init__()
self._secret = 99 # Child's own storage
def read_own(self):
return self._secret
def read_parent(self):
# now_class=Child, parent_class=Parent, obj=this instance
return private_attribute.PrivateObjSuper(Child, Parent, self)._secret
obj = Child()
obj.get_secret() # 1 — parent code sees the parent's value
obj.read_own() # 99 — child code sees its own value
obj.read_parent() # 1 — parent's per-instance value, explicitly
now_class — the private-attribute type whose code is running. Access from
any other code raises AttributeError.
parent_class — a private-attribute parent of now_class (not
now_class itself). The value is read from that class's storage for obj.
obj — an instance of now_class. An instance of a further subclass is
accepted; an instance of a sibling or of the parent is not.
The name must be a private attribute of parent_class (or of one of its
private-attribute ancestors). The lookup does not fall back to a class
attribute, to a descriptor on the class, or to an ancestor's own instance
storage — pass the class that actually stored the value. A normal instance
returns the stored object unchanged. When obj is itself a class and the
stored value defines __get__, __get__(None, obj) is called. Keyword
arguments are rejected. See the guide for
the error cases.
API reference
Name
Kind
Purpose
PrivateAttrBase
class (metaclass PrivateAttrType)
Inherit from this to make a class with private attributes.
PrivateAttrType
metaclass
The metaclass that implements the private-attribute machinery.
PrivateWrapProxy(decorator, orig=None)
decorator
Wrap an arbitrary decorator so it stays private-attribute-aware.
_PrivateWrap
class
Returned by PrivateWrapProxy; exposes .result and .funcs.
PrivateSuper(A, B, C, obj)
class
Read a parent class's class-level private attribute defined for another class; calls __get__(obj, A).
PrivateClassSuper(A, B, C, cls)
class
Classmethod flavour of PrivateSuper; calls __get__(None, cls).
PrivateObjSuper(now_class, parent_class, obj)
class
Read a parent class's per-instance private attribute from subclass code. Read-only; no class-level fallback.
create_new(func=None)
function
Register and control a custom metaclass automatically; placed in the metaclass body (or used as a decorator).
create_meta_slot(name)
function
Create the final slot (e.g. __setattr__) for a registered metaclass; empty slot or decorator.
create_slot(name)
function
Create the final slot for a private-attribute class; empty slot or decorator.
ensure_type(typ)
function
Re-inject the special-method slot descriptors and tp_traverse/tp_clear wrappers on a type.
ensure_metaclass(metaclass)
function
Re-inject the corresponding slot descriptors and wrappers on a metaclass.
Class-definition options:
Option
Type
Default
Meaning
__private_attrs__
str | Sequence[str]
()
The private attribute names.
private_func
(obj_id: int, attr_name: str) -> str
None
Custom hidden-name generator.
use_parents
bool
False
Merge ancestors' private names into this class's own set.
Custom metaclasses
To combine private attributes with another metaclass (e.g. ABCMeta), put a
create_new slot directly in the metaclass. create_new takes care of
registration and control automatically:
from abc import ABCMeta, abstractmethod
import private_attribute
class PrivateAbcMeta(ABCMeta):
__new__ = private_attribute.create_new()
class MyClass(metaclass=PrivateAbcMeta):
__private_attrs__ = ("_a",)
__slots__ = ()
@abstractmethod
def my_function(self): ...
class MyImplement(MyClass):
__private_attrs__ = ("_a",)
def __init__(self, value=1):
self._a = value
def my_function(self):
return self._a
a = MyImplement(1)
a.my_function() # 1
a._a # AttributeError: private attribute
MyClass() # TypeError: Can't instantiate abstract class ...
Custom special-method slots on the metaclass use create_meta_slot, and on a
private-attribute class use create_slot. Both take the slot name first and
work either as an empty slot or as a decorator:
class PrivateAbcMeta(ABCMeta):
__new__ = private_attribute.create_new()
__setattr__ = private_attribute.create_meta_slot("__setattr__")()
class MyClass(private_attribute.PrivateAttrBase):
__setattr__ = private_attribute.create_slot("__setattr__")()
Behavioral notes & limitations
__private_attrs__ must be a string or a sequence of strings.
Names declared in __slots__ cannot also be in __private_attrs__; however,
private attributes may still be set in methods even when __slots__ is
defined (they live in the private-attribute storage, not __dict__).
Instances of PrivateAttrBase (and subclasses) are not picklable by
default.
Private names are ultimately rewritten to a tuple of two hashes (unless a
custom private_func is supplied).
_PrivateWrap objects are transparently unwrapped back to the original
object during class creation.
Do not pass PrivateWrapProxy a decorator that itself returns a
_PrivateWrap — this raises TypeError.
A class nested inside another class cannot use the outer class's private
attributes.
If a parent class defines an attribute that is not in its
__private_attrs__ (nor a PrivateAttrType instance), a child class must not
list that name in its own __private_attrs__.
v2.1.0 — subclass code can no longer read/write a parent's private
attributes; re-declaring the name stores it separately.
v2.2.0 — a subclass must not define, in its own class body, a name that is
private to a parent, unless it declares the name in its own
__private_attrs__ or opts in with use_parents=True.
CPython may reset the special-method slot descriptors (e.g. when you assign
__getattribute__ / __setattr__). Use ensure_type (or
ensure_metaclass) to re-inject them, and avoid setting those methods on
private-attribute classes directly.
unreleased (after 3.0.4) — PrivateObjSuper(now_class, parent_class, obj)
reads a parent class's per-instance private attribute from now_class's
code. It is read-only and does not see class-level private attributes
(PrivateSuper / PrivateClassSuper remain the class-level helpers).
The private-class cache now drops a type's answer when that type is
collected, so a new type allocated at the same address is classified again.
v3 — private attribute interception is implemented through C-struct
descriptors installed as __getattribute__ / __getattr__ / __setattr__ /
__delattr__ / __del__ (and __call__ on registered metaclasses), rather
than by directly setting tp_getattro / tp_setattro / tp_finalize. Only
tp_traverse / tp_clear are set directly. A public cache keyed by object
id records attribute names already confirmed non-private, so they go
straight to the user callback without re-classification. Registered types and
created types must be heap types (static types are rejected).
Do not set __static_attributes__ on a private-attribute class; it is
removed automatically.
Building from source
The module is built with scikit-build-core
and CMake (C++17). It vendors the header-only
PicoSHA2 library for SHA-256 hashing.
git clone https://github.com/Locked-chess-official/private_attribute_cpp.git
cd private_attribute_cpp
pip install .
To build a wheel instead:
pip install build
python -m build
Set PRIVATE_ATTR_KEEP_DEBUG=1 to retain debug symbols in a Linux build
(otherwise -g0 is applied).
Running the tests
pip install pytest
python -m pytest tests/ -v
The test suite covers attribute hiding, private methods, class-level private
state, decorator wrapping, inheritance semantics (use_parents), cross-class
access (PrivateSuper, PrivateClassSuper, PrivateObjSuper), ABC/metaclass
integration, __slots__, and GC/cycle-collection regressions.