Coverage for src / lexigram / admin / resources / namespace.py: 27%

11 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-08-13 22:14 +0800

1"""Runtime namespace helper for contributor-supplied Resource classes.""" 

2 

3from __future__ import annotations 

4 

5_CACHE: dict[tuple[type, str], type] = {} 

6 

7 

8def apply_namespace(resource_cls: type, namespaced_name: str) -> type: 

9 """Return a subclass of *resource_cls* with its name set to *namespaced_name*. 

10 

11 The returned class inherits all attributes from the original and adds a 

12 ``route_prefix`` derived from the dotted name: 

13 ``"fake_pkg.users"`` → ``route_prefix = "/fake_pkg/users"``. 

14 

15 Idempotent: calling twice with the same arguments returns the same class. 

16 """ 

17 key = (resource_cls, namespaced_name) 

18 if key in _CACHE: 

19 return _CACHE[key] 

20 

21 package, _, slug = namespaced_name.partition(".") 

22 route_prefix = f"/{package}/{slug}" 

23 

24 wrapped = type( 

25 f"Namespaced_{resource_cls.__name__}", 

26 (resource_cls,), 

27 { 

28 "name": namespaced_name, 

29 "route_prefix": route_prefix, 

30 }, 

31 ) 

32 _CACHE[key] = wrapped 

33 return wrapped