Skip to content

Commit

Permalink
Add Path and Pathlike support
Browse files Browse the repository at this point in the history
  • Loading branch information
EmilianoJordan committed Dec 30, 2024
1 parent fa25111 commit e11e24e
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions src/jinja2/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@
from .ext import Extension
from .loaders import BaseLoader

StrOrBytesPath = t.Union[str, bytes, "os.PathLike[str]", "os.PathLike[bytes]"]

_env_bound = t.TypeVar("_env_bound", bound="Environment")


Expand Down Expand Up @@ -1592,7 +1594,7 @@ def __init__(self, gen: t.Iterator[str]) -> None:

def dump(
self,
fp: t.Union[str, t.IO[bytes]],
fp: t.Union["StrOrBytesPath", t.IO[bytes]],
encoding: t.Optional[str] = None,
errors: t.Optional[str] = "strict",
) -> None:
Expand All @@ -1604,17 +1606,20 @@ def dump(
Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
"""
real_fp: t.IO[bytes]

close = False

if isinstance(fp, str):
try:
real_fp = open(fp, "wb") # type: ignore[arg-type]
except TypeError:
real_fp = fp # type: ignore[assignment]
else:
close = True

if encoding is None:
encoding = "utf-8"

real_fp: t.IO[bytes] = open(fp, "wb")
close = True
else:
real_fp = fp

try:
if encoding is not None:
iterable = (x.encode(encoding, errors) for x in self) # type: ignore
Expand All @@ -1623,9 +1628,15 @@ def dump(

if hasattr(real_fp, "writelines"):
real_fp.writelines(iterable)
else:
elif hasattr(real_fp, "write"):
for item in iterable:
real_fp.write(item)
else:
raise AttributeError(
f"'{real_fp.__class__.__name__}' object has no attribute"
f" 'write' or 'writelines'"
)

finally:
if close:
real_fp.close()
Expand Down

0 comments on commit e11e24e

Please sign in to comment.