Coverage for src/appl/core/promptable/formatter.py: 81%

21 statements  

« prev     ^ index     » next       coverage.py v7.6.7, created at 2024-11-22 15:39 -0800

1from abc import ABCMeta 

2from typing import Any 

3 

4from ..types import * 

5 

6 

7# ABCMeta is required since Promptable is an abstract class 

8class FormatterMeta(ABCMeta): 

9 """Metaclass for classes that can be formatted.""" 

10 

11 def _get_format_str(cls): 

12 if fstr := getattr(cls, "fstr", None): 

13 return fstr 

14 return getattr(cls, "__format_str__", "{}") 

15 

16 def _get_format_name(cls): 

17 if name := getattr(cls, "name", None): 

18 return name 

19 if docstr := getattr(cls, "__doc__", None): 

20 return docstr 

21 return getattr(cls, "__format_name__", cls.__name__) 

22 

23 def __format__(cls, format_spec: str) -> str: 

24 fstr = cls._get_format_str() 

25 name = cls._get_format_name() 

26 return fstr.format(name, format_spec=format_spec) 

27 

28 def __repr__(cls): 

29 return cls._get_format_name() 

30 

31 

32class Formattable(metaclass=FormatterMeta): 

33 """Base class for class objects that can be formatted. 

34 

35 Example: 

36 ```py 

37 >>> class Example(Formattable): 

38 ... fstr: str = "[{}]" 

39 ... name: str = "example" 

40 >>> print(f"{Example}") 

41 [example] 

42 ``` 

43 """ 

44 

45 fstr: str 

46 name: Optional[String]