diff --git a/peps/pep-0802.rst b/peps/pep-0802.rst new file mode 100644 index 00000000000..136362a6e30 --- /dev/null +++ b/peps/pep-0802.rst @@ -0,0 +1,140 @@ +PEP: 802 +Title: Add str.template() Method to Dynamically Construct Template Objects +Author: Huang Hao Hua <13140752715@163.com> +Status: Draft +Type: Standards Track +Topic: Packaging +Requires: 750 +Created: 07-Aug-2025 +Python-Version: 3.15 +Post-History: 07-Aug-2025 + +Abstract +======== + +This PEP proposes adding a new method ``str.template(*args, **kwargs) -> Template`` +to the built-in ``str`` type. This method allows dynamically creating template +objects using the template string syntax introduced in :pep:`750`. + +This complements :pep:`750`’s ``t""`` syntax by providing a runtime equivalent API +for dynamic string templating and deferred rendering. + +Motivation +========== + +:pep:`750` introduces a structured template string syntax ``t""`` as an alternative +to ``f""`` and ``str.format()``. While ``t""`` allows compile-time template creation, +there is no standardized way to construct a ``Template`` object dynamically at runtime. + +Adding a ``str.template()`` method serves several needs: + +- Internationalization systems often generate format strings dynamically. +- Dynamic UIs or templates may assemble format strings based on user input or context. +- Reusable templates can be precompiled and stored as structured objects. +- The API would provide symmetry with ``str.format()``, making it easier to adopt. + +Specification +============= + +Method Signature +---------------- + +.. code:: python + + str.template(*args, **kwargs) -> Template + +Behavior +-------- + +- The method returns an instance of the ``Template`` class as defined by :pep:`750`. +- The string instance is treated as the template pattern. +- The passed arguments are used to bind values to the template at creation. +- Like ``str.format()``, both positional (``{0}``) and keyword (``{name}``) placeholders are supported. +- The returned ``Template`` object supports deferred rendering via ``__str__`` or explicit ``render()``. + +Example Usage +------------- + +.. code:: python + + tpl = "Hello, {name}!".template(name="Alice") + assert isinstance(tpl, Template) + print(str(tpl)) # Outputs: Hello, Alice! + + # Dynamic construction + fmt = "User {id} has status {status}." + tpl = fmt.template(id=42, status="active") + +Rationale +========= + +- Provides a runtime-compatible API for :pep:`750`’s static ``t""`` templates. +- Enables structured templates with delayed interpolation. +- Offers a migration path from ``.format()`` to structured templating. +- Useful for applications requiring dynamic template generation and reuse. +- Mirrors the mental model of ``str.format()``, reducing learning curve. + +Backwards Compatibility +======================= + +This is a fully additive proposal. ``str`` currently does not have a ``template()`` +method, so no code will be broken. + +This method has no effect on the legacy ``string.Template`` class or its behavior. + +Reference Implementation +======================== + +A sample implementation in pure Python could look like: + +.. code:: python + + class Template: + def __init__(self, pattern, *args, **kwargs): + self.pattern = pattern + self.args = args + self.kwargs = kwargs + + def __str__(self): + return self.pattern.format(*self.args, **self.kwargs) + + def str_template(self, *args, **kwargs): + return Template(self, *args, **kwargs) + + str.template = str_template + +In the CPython implementation, this would likely be implemented in C and integrated +into the ``str`` type’s method table. + +Alternatives +============ + +1. **Do nothing**: Continue using string concatenation or ``str.format()``. +2. **Use a standalone constructor**: Like ``Template.from_string(...)``. This is more verbose and less elegant. +3. **Inject into ``Template`` class only**: May reduce discoverability compared to a ``str`` method. + +Rejected Ideas +============== + +- Overloading ``str.format()`` to support structured templates. +- Adding new operators (e.g., ``@`` or ``%``) for template binding. +- Overloading ``t""`` to allow dynamic behavior (breaks simplicity and predictability). + +Open Issues +=========== + +- Whether the bound arguments are stored inside the ``Template`` object or applied at render time. +- Whether ``Template`` should expose a ``.render(...)`` method or rely solely on ``__str__``. + +References +========== + +- :pep:`750`: Structured Template Strings +- :pep:`498`: Formatted String Literals +- :pep:`3101`: Advanced String Formatting + +Copyright +========= + +This document has been placed in the public domain. +