Skip to content

Commit

Permalink
format_context now accepts only double braces. MakeFilename accepts f…
Browse files Browse the repository at this point in the history
…ilename, dirname and fileext keyword arguments and can't accept a Sequence. MakeFilename requires double braces in context formatting strings. Its run method becomes __call__.
  • Loading branch information
ynikitenko committed Apr 26, 2020
1 parent af029dc commit 5b13732
Show file tree
Hide file tree
Showing 13 changed files with 233 additions and 224 deletions.
2 changes: 1 addition & 1 deletion docs/examples/tutorial/2_split/main3.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def main():
Histogram(mesh((-10, 10), 10)),
),
]),
MakeFilename("{variable.name}"),
MakeFilename("{{variable.name}}"),
ToCSV(),
writer,
RenderLaTeX("histogram_1d.tex", "templates"),
Expand Down
4 changes: 2 additions & 2 deletions docs/examples/tutorial/2_split/main4.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,12 @@ def main():
particle,
Combine(x, y, name="xy"),
Histogram(mesh(((-10, 10), (-10, 10)), (10, 10))),
MakeFilename("{variable.particle}/{variable.name}"),
MakeFilename("{{variable.particle}}/{{variable.name}}"),
)
for particle in positron, neutron
]
),
MakeFilename("{variable.particle}/{variable.coordinate}"),
MakeFilename("{{variable.particle}}/{{variable.coordinate}}"),
ToCSV(),
writer,
RenderLaTeX(select_template, template_path="templates"),
Expand Down
4 changes: 2 additions & 2 deletions docs/examples/tutorial/2_split/performance.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def main_copybuf(data_file):
Histogram(mesh((-10, 10), 10)),
),
]),
MakeFilename("{variable.name}"),
MakeFilename("{{variable.name}}"),
ToCSV(),
# writer,
# RenderLaTeX("histogram_1d.tex", "templates"),
Expand Down Expand Up @@ -68,7 +68,7 @@ def main_no_copybuf(data_file):
],
copy_buf=False,
),
MakeFilename("{variable.name}"),
MakeFilename("{{variable.name}}"),
ToCSV(),
)
results = s.run([data_file])
Expand Down
2 changes: 1 addition & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def setup(app):
# unfortunately, this gives a warning when __call__ is missing
# https://github.com/sphinx-doc/sphinx/issues/6771
# autodoc_default_options = {
# # 'members': True,
# 'members': True,
# 'special-members': '__call__',
# # 'undoc-members': True,
# # 'exclude-members': '__weakref__'
Expand Down
1 change: 1 addition & 0 deletions docs/source/flow.rst
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ Group plots
.. autoclass:: GroupBy
.. autoclass:: GroupPlots
.. autoclass:: GroupScale

.. autoclass:: Selector
:special-members: __call__

Expand Down
21 changes: 9 additions & 12 deletions docs/source/output.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Output
.. currentmodule:: lena.output
.. autosummary::

MakeFilename
PDFToPNG
ToCSV
Writer
Expand All @@ -19,26 +20,22 @@ Output
LaTeXToPDF
RenderLaTeX

**Make filename:**

.. currentmodule:: lena.output.make_filename
.. autosummary::

MakeFilename

Output
------

.. automodule:: lena.output
.. .. automodule:: lena.output
:exclude-members: MakeFilename, LaTeXToPDF, RenderLaTeX
.. autoclass:: MakeFilename
:special-members: __call__
.. autoclass:: PDFToPNG
.. autoclass:: ToCSV
.. autofunction:: hist1d_to_csv
.. autofunction:: hist2d_to_csv
.. autoclass:: Writer

LaTeX
-----
.. currentmodule:: lena.output
.. autoclass:: LaTeXToPDF
.. autoclass:: RenderLaTeX

Make filename
-------------

.. automodule:: lena.output.make_filename
4 changes: 2 additions & 2 deletions docs/source/tutorial/2-split.rst
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ but let us unite them in one element (and improve the *cohesion* of our code):
Histogram(mesh((-10, 10), 10)),
),
]),
MakeFilename("{variable.name}"),
MakeFilename("{{variable.name}}"),
ToCSV(),
writer,
RenderLaTeX("histogram_1d.tex", "templates"),
Expand Down Expand Up @@ -265,7 +265,7 @@ and is available as a method *getter*.

*MakeFilename* accepts not only constant, but also format strings,
which take arguments from context.
In our example, *MakeFilename("{variable.name}")* creates file name from *context.variable.name*.
In our example, *MakeFilename("{{variable.name}}")* creates file name from *context.variable.name*.

Note also that since two *Writers* do the same thing, we rewrote them as one object.

Expand Down
2 changes: 1 addition & 1 deletion docs/source/tutorial/answers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ Delete the first *MakeFilename* and change the second one to

.. code-block:: python
MakeFilename("{variable.particle}/{variable.name}")
MakeFilename("{{variable.particle}}/{{variable.name}}")
Ex. 3
^^^^^
Expand Down
57 changes: 34 additions & 23 deletions lena/context/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,13 @@ def format_context(format_str):
It is recommended to use jinja2.Template.
Use this function only if you don't have jinja2.
*format_str* is an ordinary Python format string.
*format_str* is a Python format string with double braces
instead of single ones.
It must contain all non-empty replacement fields,
and only simplest formatting without attribute lookup.
Example:
>>> f = format_context("{x}")
>>> f = format_context("{{x}}")
>>> f({"x": 10})
'10'
Expand All @@ -73,23 +74,36 @@ def format_context(format_str):
Keys can be nested using a dot, for example:
>>> f = format_context("{x.y}")
>>> f({"x": {"y": 10}})
'10'
>>> f = format_context("{{x.y}}_{{z}}")
>>> f({"x": {"y": 10}, "z": 1})
'10_1'
This function does not work with unbalanced braces.
If a simple check fails, :exc:`.LenaValueError` is raised.
If *format_str* is not a string, :exc:`.LenaTypeError` is raised.
All other errors are raised only during formatting.
If context doesn't contain the needed key,
:exc:`.LenaKeyError` is raised.
Note that string formatting can also raise
a :exc:`KeyError` or an :exc:`IndexError`,
Note that string formatting can also raise a :exc:`ValueError`,
so it is recommended to test your formatters before using them.
"""
if not isinstance(format_str, str):
raise lena.core.LenaTypeError(
"format_str must be a string, {} given".format(format_str)
)

# prohibit single or unbalanced braces
if format_str.count('{') != format_str.count('}'):
raise lena.core.LenaValueError("unbalanced braces in '{}'".format(format_str))
if '{' in format_str and not '{{' in format_str:
raise lena.core.LenaValueError(
"double braces must be used for formatting instead of '{}'"
.format(format_str)
)

# new format: now double braces instead of single ones.
# but the algorithm may be left unchanged.
format_str = format_str.replace("{{", "{").replace("}}", "}")
new_str = []
new_args = []
prev_char = ''
Expand All @@ -104,12 +118,14 @@ def format_context(format_str):
continue
while c == '{' and ind < len(format_str):
new_str.append(c)
if prev_char == '{':
prev_char = ''
within_field = False
else:
prev_char = c
within_field = True
# literal formatting { are not allowed
# if prev_char == '{':
# prev_char = ''
# within_field = False
# else:
prev_char = c
within_field = True

ind += 1
c = format_str[ind]
if within_field:
Expand All @@ -128,17 +144,12 @@ def format_context(format_str):
def _format_context(context):
new_args = []
for arg in args:
# LenaKeyError may be raised
new_args.append(lena.context.get_recursively(context, arg))
try:
s = format_str.format(*new_args)
except KeyError:
raise lena.core.LenaKeyError(
"keyword arguments of {} not found in kwargs {}".format(
format_str, new_kwargs
)
)
else:
return s
# other exceptions, like ValueError
# (for bad string formatting) may be raised.
s = format_str.format(*new_args)
return s
return _format_context


Expand Down

0 comments on commit 5b13732

Please sign in to comment.