private-attribute-cpp 2.2.6__tar.gz → 2.2.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. private_attribute_cpp-2.2.8/PKG-INFO +416 -0
  2. private_attribute_cpp-2.2.8/README.md +406 -0
  3. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/private_attribute.cpp +281 -171
  4. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/pyproject.toml +10 -1
  5. private_attribute_cpp-2.2.6/.github/dependabot.yml +0 -6
  6. private_attribute_cpp-2.2.6/.github/workflows/build-android.yml +0 -185
  7. private_attribute_cpp-2.2.6/.github/workflows/lint.yml +0 -10
  8. private_attribute_cpp-2.2.6/.github/workflows/python-publish.yml +0 -270
  9. private_attribute_cpp-2.2.6/.github/workflows/test.yml +0 -97
  10. private_attribute_cpp-2.2.6/.github/workflows/update-bot.yml +0 -42
  11. private_attribute_cpp-2.2.6/.gitignore +0 -20
  12. private_attribute_cpp-2.2.6/.pre-commit-config.yaml +0 -22
  13. private_attribute_cpp-2.2.6/.update-bot/update_picosha2.py +0 -37
  14. private_attribute_cpp-2.2.6/PKG-INFO +0 -264
  15. private_attribute_cpp-2.2.6/README.md +0 -254
  16. private_attribute_cpp-2.2.6/ci/android/build_python.sh +0 -312
  17. private_attribute_cpp-2.2.6/ci/android/common.sh +0 -222
  18. private_attribute_cpp-2.2.6/ci/android/pydroid3.sh +0 -54
  19. private_attribute_cpp-2.2.6/ci/android/run.sh +0 -70
  20. private_attribute_cpp-2.2.6/ci/android/termux.sh +0 -48
  21. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/CMakeLists.txt +0 -0
  22. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/LICENSE +0 -0
  23. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/picosha2.h +0 -0
  24. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/private_attribute.pyi +0 -0
  25. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/tests/test_attr_classify_owner.py +0 -0
  26. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/tests/test_class_private_attrs.py +0 -0
  27. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/tests/test_gc_collect.py +0 -0
  28. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/tests/test_init_subclass.py +0 -0
  29. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/tests/test_private_abc.py +0 -0
  30. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/tests/test_private_attrs.py +0 -0
  31. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/tests/test_private_func.py +0 -0
  32. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/tests/test_private_inheritance.py +0 -0
  33. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/tests/test_private_method.py +0 -0
  34. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/tests/test_private_wrap.py +0 -0
  35. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/tests/test_slots_cycle.py +0 -0
  36. {private_attribute_cpp-2.2.6 → private_attribute_cpp-2.2.8}/tests/test_use_parents.py +0 -0
@@ -0,0 +1,416 @@
1
+ Metadata-Version: 2.4
2
+ Name: private_attribute_cpp
3
+ Version: 2.2.8
4
+ Summary: A Python package that provides a way to define private attributes in C++ implementation.
5
+ Author-Email: HuangHaoHua <13140752715@example.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Locked-chess-official/private_attribute_cpp
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+
11
+ # private_attribute_cpp
12
+
13
+ [![PyPI](https://img.shields.io/pypi/v/private-attribute-cpp)](https://pypi.org/project/private-attribute-cpp/)
14
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
15
+
16
+ True C++-style **private attributes** for Python, enforced at the C level.
17
+
18
+ A C++ extension module (`private_attribute`) that lets you declare attributes
19
+ that are only accessible from *inside* the class that owns them — genuinely
20
+ hidden from the outside world, from subclasses, and from `hasattr()`, `dir()`,
21
+ and `obj.__dict__`. Unlike Python's name-mangling (`_Class__name`) and the
22
+ leading-underscore convention, these attributes cannot be reached at all from
23
+ outside the declaring class's own code.
24
+
25
+ > **Note:** CPython only. Requires Python ≥ 3.10.
26
+
27
+ ---
28
+
29
+ ## Table of contents
30
+
31
+ - [Why?](#why)
32
+ - [Installation](#installation)
33
+ - [Quick start](#quick-start)
34
+ - [Core concepts](#core-concepts)
35
+ - [Declaring private attributes](#declaring-private-attributes)
36
+ - [Custom name generation (`private_func`)](#custom-name-generation-private_func)
37
+ - [Decorated methods (`PrivateWrapProxy`)](#decorated-methods-privatewrapproxy)
38
+ - [Inheritance and `use_parents`](#inheritance-and-use_parents)
39
+ - [API reference](#api-reference)
40
+ - [Custom metaclasses](#custom-metaclasses)
41
+ - [Behavioral notes & limitations](#behavioral-notes--limitations)
42
+ - [Building from source](#building-from-source)
43
+ - [Running the tests](#running-the-tests)
44
+ - [License](#license)
45
+
46
+ ---
47
+
48
+ ## Why?
49
+
50
+ Python gives you a *convention* (`_private`) and a *name-mangling trick*
51
+ (`__name` → `_ClassName__name`), but neither is an actual access barrier. Any
52
+ code that knows (or can guess) the mangled name can still read and mutate your
53
+ "private" state.
54
+
55
+ `private_attribute` implements the real thing in C++:
56
+
57
+ - Private attributes are **not stored in `__dict__`**.
58
+ - They are **unreachable from outside** the class that declares them — including
59
+ from subclasses and from `getattr`/`hasattr`/`dir`.
60
+ - Inside the declaring class, they look and behave like ordinary attributes.
61
+
62
+ It does this by rewriting attribute access in `tp_getattro` / `tp_setattro` and
63
+ storing private values under generated, collision-resistant names (a tuple of
64
+ two SHA-256 hashes).
65
+
66
+ ---
67
+
68
+ ## Installation
69
+
70
+ ```bash
71
+ pip install private-attribute-cpp
72
+ ```
73
+
74
+ Prebuilt wheels are published for CPython 3.10–3.15 (including free-threaded
75
+ `t` builds) across Linux, macOS, and Windows.
76
+
77
+ ---
78
+
79
+ ## Quick start
80
+
81
+ ```python
82
+ from private_attribute import PrivateAttrBase
83
+
84
+ class BankAccount(PrivateAttrBase):
85
+ __private_attrs__ = ["_balance"]
86
+
87
+ def __init__(self, balance):
88
+ self._balance = balance
89
+
90
+ def deposit(self, amount):
91
+ self._balance += amount # ✅ accessible inside the class
92
+
93
+ @property
94
+ def balance(self):
95
+ return self._balance
96
+
97
+ acct = BankAccount(100)
98
+ print(acct.balance) # 100
99
+ acct.deposit(50)
100
+ print(acct.balance) # 150
101
+
102
+ print(hasattr(acct, "_balance")) # False — truly hidden
103
+ print(acct._balance) # AttributeError: private attribute
104
+ ```
105
+
106
+ ---
107
+
108
+ ## Core concepts
109
+
110
+ ### Declaring private attributes
111
+
112
+ List the private names in the `__private_attrs__` class attribute:
113
+
114
+ ```python
115
+ from private_attribute import PrivateAttrBase
116
+
117
+ class MyClass(PrivateAttrBase):
118
+ __private_attrs__ = ["a", "b", "c"] # string, or a sequence of strings
119
+
120
+ def __init__(self):
121
+ self.a = 1
122
+ self.b = 2
123
+ self.c = 3
124
+
125
+ def show(self):
126
+ print(self.a, self.b, self.c) # (1, 2, 3) — visible inside
127
+
128
+ obj = MyClass()
129
+ obj.show() # 1 2 3
130
+ print(hasattr(obj, "a")) # False
131
+ print(hasattr(obj, "b")) # False
132
+ print(hasattr(obj, "c")) # False
133
+ ```
134
+
135
+ - Private attributes may be set on **instances** *or* on the **class itself**
136
+ (class-level private state, e.g. for `@classmethod`).
137
+ - They also cover **private methods**: declare a method name in
138
+ `__private_attrs__` and it becomes callable only from the class's own code.
139
+ - They work alongside `__slots__` (see notes below).
140
+
141
+ ### Custom name generation (`private_func`)
142
+
143
+ By default private values are stored under generated hash names. You can
144
+ control how the storage name is derived with a `private_func` callable, which
145
+ receives the object id and the attribute name:
146
+
147
+ ```python
148
+ from private_attribute import PrivateAttrBase
149
+
150
+ def my_generate_func(obj_id, attr_name):
151
+ return f"_hidden_{obj_id}_{attr_name}"
152
+
153
+ class MyClass(PrivateAttrBase, private_func=my_generate_func):
154
+ __private_attrs__ = ["secret"]
155
+
156
+ def __init__(self):
157
+ self.secret = 42
158
+
159
+ def read(self):
160
+ return self.secret
161
+ ```
162
+
163
+ `private_func` may be passed either as a keyword in the class definition (shown
164
+ above) or on `PrivateAttrBase` itself. It is optional; the default generates a
165
+ tuple of two SHA-256 hashes.
166
+
167
+ ### Decorated methods (`PrivateWrapProxy`)
168
+
169
+ Decorators that return a plain wrapper object (anything other than
170
+ `property` / `classmethod` / `staticmethod`) would normally break private
171
+ attribute access, because the wrapper's bytecode is not recognized as
172
+ belonging to the class. `PrivateWrapProxy` makes arbitrary decorators
173
+ compatible:
174
+
175
+ ```python
176
+ from private_attribute import PrivateAttrBase, PrivateWrapProxy
177
+
178
+ def deco(func):
179
+ def wrapper(*args, **kwargs):
180
+ return func(*args, **kwargs)
181
+ return wrapper
182
+
183
+ class MyClass(PrivateAttrBase):
184
+ __private_attrs__ = ["a", "b"]
185
+
186
+ @PrivateWrapProxy(deco)
187
+ def method1(self):
188
+ return self.a
189
+
190
+ @PrivateWrapProxy(deco)
191
+ @PrivateWrapProxy(deco)
192
+ def method2(self):
193
+ return self.b
194
+ ```
195
+
196
+ `PrivateWrapProxy(decorator)` returns a `_PrivateWrap` object that wraps the
197
+ decorator application. It exposes two public attributes:
198
+
199
+ - **`.result`** — the final decorated result.
200
+ - **`.funcs`** — a read-only list proxy (`_listproxy`) of the original (pre-decoration) functions.
201
+
202
+ To stack decorators, resolve name conflicts, or fix decorator ordering, chain
203
+ `.result.<attr>` onto the wrapped method and pass the method itself as the
204
+ second argument (which saves the previous functions):
205
+
206
+ ```python
207
+ class MyClass(PrivateAttrBase):
208
+ __private_attrs__ = ["a", "b", "c"]
209
+
210
+ @PrivateWrapProxy(deco1)
211
+ def method1(self):
212
+ return self.a
213
+
214
+ @PrivateWrapProxy(method1.result.name1, method1)
215
+ @PrivateWrapProxy(method1.result.name2, method1)
216
+ def method1(self): # final implementation; earlier ones are kept
217
+ return self.b
218
+
219
+ @PrivateWrapProxy(deco2)
220
+ def method2(self):
221
+ return self.c
222
+ ```
223
+
224
+ The `_PrivateWrap` object is transparent in normal use: it forwards
225
+ `__getattr__`, `__call__`, and descriptor `__get__` to its `.result`, so callers
226
+ interact with the wrapped method as usual.
227
+
228
+ ### Inheritance and `use_parents`
229
+
230
+ Since v2.1.0, **a subclass's code cannot access its parent's private
231
+ attributes** — a parent's private attribute is reachable only from the parent's
232
+ own code, or from a class that re-declares the same name in its own
233
+ `__private_attrs__`. When a subclass re-declares the same name, the two are
234
+ stored **separately** (instance attributes per declaring class, class-level
235
+ attributes per class).
236
+
237
+ Since v2.2.0, you can opt in to inheriting all ancestors' private names with
238
+ `use_parents=True`:
239
+
240
+ ```python
241
+ class Parent(PrivateAttrBase):
242
+ __private_attrs__ = ["_secret"]
243
+ def __init__(self):
244
+ self._secret = 1
245
+ def get_secret(self):
246
+ return self._secret
247
+
248
+ class Child(Parent, use_parents=True):
249
+ __private_attrs__ = []
250
+ def __init__(self):
251
+ super().__init__()
252
+ self._secret = 99 # stored in Child's own storage
253
+ def read_own(self):
254
+ return self._secret
255
+
256
+ obj = Child()
257
+ obj.get_secret() # 1 — parent code sees the parent's value
258
+ obj.read_own() # 99 — child code sees its own value
259
+ ```
260
+
261
+ The merged names live in the subclass's **own** storage — they never overwrite
262
+ the parent's values. The Python-level `__private_attrs__` tuple is left
263
+ unchanged; only the internal name set is merged. Default is `False`.
264
+
265
+ ---
266
+
267
+ ## API reference
268
+
269
+ | Name | Kind | Purpose |
270
+ | --- | --- | --- |
271
+ | `PrivateAttrBase` | class (metaclass `PrivateAttrType`) | Inherit from this to make a class with private attributes. |
272
+ | `PrivateAttrType` | metaclass | The metaclass that implements the private-attribute machinery. |
273
+ | `PrivateWrapProxy(decorator, orig=None)` | decorator | Wrap an arbitrary decorator so it stays private-attribute-aware. |
274
+ | `_PrivateWrap` | class | Returned by `PrivateWrapProxy`; exposes `.result` and `.funcs`. |
275
+ | `prepare(name, bases, attrs, **kwds)` | function | Context manager for building private-attribute classes in a custom metaclass. |
276
+ | `postprocess(typ, temp)` | function | Finalize a class created via `prepare`. |
277
+ | `register_metaclass(metaclass)` | function | Register a custom metaclass so it can produce private-attribute classes. |
278
+ | `ensure_type(typ)` | function | Reset `tp_getattro`/`tp_setattro`/`tp_finalizer` slots on a type. |
279
+ | `ensure_metaclass(metaclass)` | function | Reset the corresponding slots on a metaclass. |
280
+
281
+ Class-definition options:
282
+
283
+ | Option | Type | Default | Meaning |
284
+ | --- | --- | --- | --- |
285
+ | `__private_attrs__` | `str` \| `Sequence[str]` | `()` | The private attribute names. |
286
+ | `private_func` | `(obj_id: int, attr_name: str) -> str` | `None` | Custom hidden-name generator. |
287
+ | `use_parents` | `bool` | `False` | Merge ancestors' private names into this class's own set. |
288
+
289
+ ---
290
+
291
+ ## Custom metaclasses
292
+
293
+ To combine private attributes with another metaclass (e.g. `ABCMeta`), use the
294
+ `prepare` / `postprocess` pair and register the metaclass:
295
+
296
+ ```python
297
+ from abc import ABCMeta, abstractmethod
298
+ import private_attribute
299
+
300
+ class PrivateAbcMeta(ABCMeta):
301
+ def __new__(cls, name, bases, attrs, **kwargs):
302
+ with private_attribute.prepare(name, bases, attrs, **kwargs) as temp:
303
+ typ = super().__new__(cls, temp.name, temp.bases, temp.attrs, **temp.kwds)
304
+ private_attribute.postprocess(typ, temp) # or temp.postprocess(typ)
305
+ return typ
306
+
307
+ private_attribute.register_metaclass(PrivateAbcMeta)
308
+
309
+ class MyClass(metaclass=PrivateAbcMeta):
310
+ __private_attrs__ = ("_a",)
311
+ __slots__ = ()
312
+
313
+ @abstractmethod
314
+ def my_function(self): ...
315
+
316
+ class MyImplement(MyClass):
317
+ __private_attrs__ = ("_a",)
318
+ def __init__(self, value=1):
319
+ self._a = value
320
+ def my_function(self):
321
+ return self._a
322
+
323
+ a = MyImplement(1)
324
+ a.my_function() # 1
325
+ a._a # AttributeError: private attribute
326
+ MyClass() # TypeError: Can't instantiate abstract class ...
327
+ ```
328
+
329
+ `prepare(...)` returns a temporary object exposing `.name`, `.bases`, `.attrs`,
330
+ and `.kwds` (and, since v2.1.17, a `.postprocess(typ)` shortcut). Since v2.2.3
331
+ it is a context manager (`with`), which guarantees the internal creation lock is
332
+ released even if construction fails.
333
+
334
+ ---
335
+
336
+ ## Behavioral notes & limitations
337
+
338
+ - `__private_attrs__` must be a string or a sequence of strings.
339
+ - Names declared in `__slots__` cannot also be in `__private_attrs__`; however,
340
+ private attributes may still be *set* in methods even when `__slots__` is
341
+ defined (they live in the private-attribute storage, not `__dict__`).
342
+ - Instances of `PrivateAttrBase` (and subclasses) are **not picklable** by
343
+ default.
344
+ - Private names are ultimately rewritten to a tuple of two hashes (unless a
345
+ custom `private_func` is supplied).
346
+ - `_PrivateWrap` objects are transparently unwrapped back to the original
347
+ object during class creation.
348
+ - Do **not** pass `PrivateWrapProxy` a decorator that itself returns a
349
+ `_PrivateWrap` — this raises `TypeError`.
350
+ - A class nested inside another class cannot use the outer class's private
351
+ attributes.
352
+ - If a parent class defines an attribute that is *not* in its
353
+ `__private_attrs__` (nor a `PrivateAttrType` instance), a child class must not
354
+ list that name in its own `__private_attrs__`.
355
+ - **v2.1.0** — subclass code can no longer read/write a parent's private
356
+ attributes; re-declaring the name stores it separately.
357
+ - **v2.2.0** — a subclass must not define, in its own class body, a name that is
358
+ private to a parent, unless it declares the name in its own
359
+ `__private_attrs__` or opts in with `use_parents=True`.
360
+ - **v2.2.1** — `prepare` locks private-attribute-type creation so only one type
361
+ is being built (`type.__new__`) at a time; `postprocess` unlocks it. The lock
362
+ is released automatically on failure.
363
+ - **v2.2.3** — prefer the `with` form of `prepare`/`postprocess` to guarantee
364
+ the lock is released.
365
+ - CPython may change `tp_getattro` / `tp_setattro` when you assign
366
+ `__getattribute__` / `__setattr__`. Use `ensure_type` (or `ensure_metaclass`)
367
+ to reset those slots, and avoid setting those methods on private-attribute
368
+ classes directly.
369
+ - `register_metaclass` requires a metaclass that supports weak references.
370
+ - Do **not** set `__static_attributes__` on a private-attribute class; it is
371
+ removed automatically.
372
+
373
+ ---
374
+
375
+ ## Building from source
376
+
377
+ The module is built with [scikit-build-core](https://scikit-build-core.readthedocs.io/)
378
+ and CMake (C++17). It vendors the header-only
379
+ [PicoSHA2](https://github.com/okdshin/PicoSHA2) library for SHA-256 hashing.
380
+
381
+ ```bash
382
+ git clone https://github.com/Locked-chess-official/private_attribute_cpp.git
383
+ cd private_attribute_cpp
384
+ pip install .
385
+ ```
386
+
387
+ To build a wheel instead:
388
+
389
+ ```bash
390
+ pip install build
391
+ python -m build
392
+ ```
393
+
394
+ Set `PRIVATE_ATTR_KEEP_DEBUG=1` to retain debug symbols in a Linux build
395
+ (otherwise `-g0` is applied).
396
+
397
+ ---
398
+
399
+ ## Running the tests
400
+
401
+ ```bash
402
+ pip install pytest
403
+ python -m pytest tests/ -v
404
+ ```
405
+
406
+ The test suite covers attribute hiding, private methods, class-level private
407
+ state, decorator wrapping, inheritance semantics (`use_parents`), ABC/metaclass
408
+ integration, `__slots__`, and GC/cycle-collection regressions.
409
+
410
+ ---
411
+
412
+ ## License
413
+
414
+ [MIT](LICENSE) © 2026 Locked-chess-official.
415
+
416
+ PicoSHA2 is distributed under the MIT License (© 2017 okdshin).