Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery refactored main branch #1

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions scripts/generate_identifier_pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def get_characters():
for cp in range(sys.maxunicode + 1):
s = chr(cp)

if ("a" + s).isidentifier() and not re.match(r"\w", s):
if f"a{s}".isidentifier() and not re.match(r"\w", s):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_characters refactored with the following changes:

yield s


Expand All @@ -45,8 +45,7 @@ def build_pattern(ranges):
if a == b: # single char
out.append(a)
elif ord(b) - ord(a) == 1: # two chars, range is redundant
out.append(a)
out.append(b)
out.extend((a, b))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function build_pattern refactored with the following changes:

else:
out.append(f"{a}-{b}")

Expand Down
5 changes: 1 addition & 4 deletions src/jinja2/async_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,7 @@ def wrapper(*args, **kwargs): # type: ignore
if need_eval_context:
args = args[1:]

if b:
return async_func(*args, **kwargs)

return normal_func(*args, **kwargs)
return async_func(*args, **kwargs) if b else normal_func(*args, **kwargs)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function async_variant refactored with the following changes:


if need_eval_context:
wrapper = pass_eval_context(wrapper)
Expand Down
36 changes: 11 additions & 25 deletions src/jinja2/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None:
self.write(f"environment.call_unop(context, {op!r}, ")
self.visit(node.node, frame)
else:
self.write("(" + op)
self.write(f"({op}")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _make_unop refactored with the following changes:

self.visit(node.node, frame)

self.write(")")
Expand All @@ -116,10 +116,7 @@ def generate(
)
generator.visit(node)

if stream is None:
return generator.stream.getvalue() # type: ignore

return None
return generator.stream.getvalue() if stream is None else None
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function generate refactored with the following changes:

This removes the following comments ( why? ):

# type: ignore



def has_safe_repr(value: t.Any) -> bool:
Expand Down Expand Up @@ -596,10 +593,7 @@ def enter_frame(self, frame: Frame) -> None:

def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None:
if not with_python_scope:
undefs = []
for target in frame.symbols.loads:
undefs.append(target)
if undefs:
if undefs := list(frame.symbols.loads):
Comment on lines -599 to +596
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CodeGenerator.leave_frame refactored with the following changes:

self.writeline(f"{' = '.join(undefs)} = missing")

def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str:
Expand Down Expand Up @@ -761,18 +755,14 @@ def get_context_ref(self) -> str:

def get_resolve_func(self) -> str:
target = self._context_reference_stack[-1]
if target == "context":
return "resolve"
return f"{target}.resolve"
return "resolve" if target == "context" else f"{target}.resolve"
Comment on lines -764 to +758
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CodeGenerator.get_resolve_func refactored with the following changes:


def derive_context(self, frame: Frame) -> str:
return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})"

def parameter_is_undeclared(self, target: str) -> bool:
"""Checks if a given target is an undeclared parameter."""
if not self._param_def_block:
return False
return target in self._param_def_block[-1]
return target in self._param_def_block[-1] if self._param_def_block else False
Comment on lines -773 to +765
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CodeGenerator.parameter_is_undeclared refactored with the following changes:


def push_assign_tracking(self) -> None:
"""Pushes a new layer for assignment tracking."""
Expand Down Expand Up @@ -909,7 +899,7 @@ def visit_Template(
# at this point we now have the blocks collected and can visit them too.
for name, block in self.blocks.items():
self.writeline(
f"{self.func('block_' + name)}(context, missing=missing{envenv}):",
f"{self.func(f'block_{name}')}(context, missing=missing{envenv}):",
Comment on lines -912 to +902
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CodeGenerator.visit_Template refactored with the following changes:

block,
1,
)
Expand Down Expand Up @@ -954,11 +944,7 @@ def visit_Block(self, node: nodes.Block, frame: Frame) -> None:
self.indent()
level += 1

if node.scoped:
context = self.derive_context(frame)
else:
context = self.get_context_ref()

context = self.derive_context(frame) if node.scoped else self.get_context_ref()
Comment on lines -957 to +947
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CodeGenerator.visit_Block refactored with the following changes:

if node.required:
self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node)
self.indent()
Expand Down Expand Up @@ -1530,9 +1516,9 @@ def visit_Output(self, node: nodes.Output, frame: Frame) -> None:
val = self._output_const_repr(item)

if frame.buffer is None:
self.writeline("yield " + val)
self.writeline(f"yield {val}")
else:
self.writeline(val + ",")
self.writeline(f"{val},")
Comment on lines -1533 to +1521
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CodeGenerator.visit_Output refactored with the following changes:

else:
if frame.buffer is None:
self.writeline("yield ", item)
Expand Down Expand Up @@ -1860,7 +1846,7 @@ def visit_Call(
self.write("))")

def visit_Keyword(self, node: nodes.Keyword, frame: Frame) -> None:
self.write(node.key + "=")
self.write(f"{node.key}=")
Comment on lines -1863 to +1849
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CodeGenerator.visit_Keyword refactored with the following changes:

self.visit(node.value, frame)

# -- Unused nodes for extensions
Expand All @@ -1880,7 +1866,7 @@ def visit_MarkSafeIfAutoescape(
def visit_EnvironmentAttribute(
self, node: nodes.EnvironmentAttribute, frame: Frame
) -> None:
self.write("environment." + node.name)
self.write(f"environment.{node.name}")
Comment on lines -1883 to +1869
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CodeGenerator.visit_EnvironmentAttribute refactored with the following changes:


def visit_ExtensionAttribute(
self, node: nodes.ExtensionAttribute, frame: Frame
Expand Down
6 changes: 1 addition & 5 deletions src/jinja2/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,7 @@ def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any
# Start with the current template context.
ctx: "t.Optional[Context]" = real_locals.get("context")

if ctx is not None:
data: t.Dict[str, t.Any] = ctx.get_all().copy()
else:
data = {}

data = ctx.get_all().copy() if ctx is not None else {}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_template_locals refactored with the following changes:

# Might be in a derived context that only sets local variables
# rather than pushing a context. Local variables follow the scheme
# l_depth_name. Find the highest-depth local that has a value for
Expand Down
54 changes: 18 additions & 36 deletions src/jinja2/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,7 @@ def create_cache(
if size == 0:
return None

if size < 0:
return {}

return LRUCache(size) # type: ignore
return {} if size < 0 else LRUCache(size)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function create_cache refactored with the following changes:

This removes the following comments ( why? ):

# type: ignore



def copy_cache(
Expand All @@ -99,10 +96,7 @@ def copy_cache(
if cache is None:
return None

if type(cache) is dict:
return {}

return LRUCache(cache.capacity) # type: ignore
return {} if type(cache) is dict else LRUCache(cache.capacity)
Comment on lines -102 to +99
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function copy_cache refactored with the following changes:

This removes the following comments ( why? ):

# type: ignore



def load_extensions(
Expand Down Expand Up @@ -535,11 +529,7 @@ def _filter_test_common(
args.insert(0, context)
elif pass_arg is _PassArg.eval_context:
if eval_ctx is None:
if context is not None:
eval_ctx = context.eval_ctx
else:
eval_ctx = EvalContext(self)

eval_ctx = context.eval_ctx if context is not None else EvalContext(self)
Comment on lines -538 to +532
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Environment._filter_test_common refactored with the following changes:

args.insert(0, eval_ctx)
elif pass_arg is _PassArg.environment:
args.insert(0, self)
Expand Down Expand Up @@ -633,7 +623,7 @@ def lex(
of the extensions to be applied you have to filter source through
the :meth:`preprocess` method.
"""
source = str(source)
source = source
Comment on lines -636 to +626
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Environment.lex refactored with the following changes:

try:
return self.lexer.tokeniter(source, name, filename)
except TemplateSyntaxError:
Expand All @@ -652,7 +642,7 @@ def preprocess(
return reduce(
lambda s, e: e.preprocess(s, name, filename),
self.iter_extensions(),
str(source),
source,
Comment on lines -655 to +645
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Environment.preprocess refactored with the following changes:

)

def _tokenize(
Expand Down Expand Up @@ -1439,9 +1429,7 @@ def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModul
raise RuntimeError("Module is not available in async mode.")

if ctx is not None:
keys = ctx.globals_keys - self.globals.keys()

if keys:
if keys := ctx.globals_keys - self.globals.keys():
Comment on lines -1442 to +1432
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Template._get_default_module refactored with the following changes:

return self.make_module({k: ctx.parent[k] for k in keys})

if self._module is None:
Expand All @@ -1453,9 +1441,7 @@ async def _get_default_module_async(
self, ctx: t.Optional[Context] = None
) -> "TemplateModule":
if ctx is not None:
keys = ctx.globals_keys - self.globals.keys()

if keys:
if keys := ctx.globals_keys - self.globals.keys():
Comment on lines -1456 to +1444
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Template._get_default_module_async refactored with the following changes:

return await self.make_module_async({k: ctx.parent[k] for k in keys})

if self._module is None:
Expand Down Expand Up @@ -1483,17 +1469,19 @@ def get_corresponding_lineno(self, lineno: int) -> int:
"""Return the source line number of a line number in the
generated bytecode as they are not in sync.
"""
for template_line, code_line in reversed(self.debug_info):
if code_line <= lineno:
return template_line
return 1
return next(
(
template_line
for template_line, code_line in reversed(self.debug_info)
if code_line <= lineno
),
1,
)
Comment on lines -1486 to +1479
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Template.get_corresponding_lineno refactored with the following changes:

  • Use the built-in function next instead of a for-loop (use-next)


@property
def is_up_to_date(self) -> bool:
"""If this variable is `False` there is a newer version available."""
if self._uptodate is None:
return True
return self._uptodate()
return True if self._uptodate is None else self._uptodate()
Comment on lines -1494 to +1484
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Template.is_up_to_date refactored with the following changes:


@property
def debug_info(self) -> t.List[t.Tuple[int, int]]:
Expand All @@ -1507,10 +1495,7 @@ def debug_info(self) -> t.List[t.Tuple[int, int]]:
return []

def __repr__(self) -> str:
if self.name is None:
name = f"memory:{id(self):x}"
else:
name = repr(self.name)
name = f"memory:{id(self):x}" if self.name is None else repr(self.name)
Comment on lines -1510 to +1498
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Template.__repr__ refactored with the following changes:

return f"<{type(self).__name__} {name}>"


Expand Down Expand Up @@ -1547,10 +1532,7 @@ def __str__(self) -> str:
return concat(self._body_stream)

def __repr__(self) -> str:
if self.__name__ is None:
name = f"memory:{id(self):x}"
else:
name = repr(self.__name__)
name = f"memory:{id(self):x}" if self.__name__ is None else repr(self.__name__)
Comment on lines -1550 to +1535
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TemplateModule.__repr__ refactored with the following changes:

return f"<{type(self).__name__} {name}>"


Expand Down
7 changes: 3 additions & 4 deletions src/jinja2/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,9 @@ def __str__(self) -> str:

# otherwise attach some stuff
location = f"line {self.lineno}"
name = self.filename or self.name
if name:
if name := self.filename or self.name:
location = f'File "{name}", {location}'
lines = [t.cast(str, self.message), " " + location]
lines = [t.cast(str, self.message), f" {location}"]
Comment on lines -115 to +117
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TemplateSyntaxError.__str__ refactored with the following changes:


# if the source is set, add the line to the output
if self.source is not None:
Expand All @@ -124,7 +123,7 @@ def __str__(self) -> str:
except IndexError:
pass
else:
lines.append(" " + line.strip())
lines.append(f" {line.strip()}")

return "\n".join(lines)

Expand Down
11 changes: 2 additions & 9 deletions src/jinja2/ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,12 +355,9 @@ def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:
"""Parse a translatable tag."""
lineno = next(parser.stream).lineno

context = None
context_token = parser.stream.next_if("string")

if context_token is not None:
context = context_token.value

context = context_token.value if context_token is not None else None
Comment on lines -358 to +360
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InternationalizationExtension.parse refactored with the following changes:

# find all the variables referenced. Additionally a variable can be
# defined in the body of the trans block too, but this is checked at
# a later state.
Expand Down Expand Up @@ -712,11 +709,7 @@ def extract_from_ast(
if not out:
continue
else:
if len(strings) == 1:
out = strings[0]
else:
out = tuple(strings)

out = strings[0] if len(strings) == 1 else tuple(strings)
Comment on lines -715 to +712
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function extract_from_ast refactored with the following changes:

yield node.lineno, node.node.name, out


Expand Down
Loading