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

Feature: Return namedtuples for get_format_args #93

Open
wants to merge 3 commits into
base: master
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
14 changes: 11 additions & 3 deletions boltons/formatutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@
import re
from string import Formatter

try:
from boltons.namedutils import namedtuple
except ImportError:
from collections import namedtuple

__all__ = ['DeferredValue', 'get_format_args', 'tokenize_format_str',
'construct_format_field_str', 'infer_positional_format_args',
Expand Down Expand Up @@ -117,6 +121,10 @@ def infer_positional_format_args(fstr):
[(x, float) for x in _FLOATCHARS])
_TYPE_MAP['s'] = str

FormatArgs = namedtuple('FormatArgs', ('positional', 'named'))
PositionalFormatArg = namedtuple('PositionalFormatArg', ('index', 'type'))
NamedFormatArg = namedtuple('NamedFormatArg', ('key', 'type'))


def get_format_args(fstr):
"""
Expand All @@ -142,9 +150,9 @@ def _add_arg(argname, type_char='s'):
_dedup.add(argname)
argtype = _TYPE_MAP.get(type_char, str) # TODO: unicode
try:
fargs.append((int(argname), argtype))
fargs.append(PositionalFormatArg(int(argname), argtype))
except ValueError:
fkwargs.append((argname, argtype))
fkwargs.append(NamedFormatArg(argname, argtype))

for lit, fname, fspec, conv in formatter.parse(fstr):
if fname is not None:
Expand All @@ -162,7 +170,7 @@ def _add_arg(argname, type_char='s'):
# TODO: positional and anon args not allowed here.
if subfname is not None:
_add_arg(subfname)
return fargs, fkwargs
return FormatArgs(fargs, fkwargs)


def tokenize_format_str(fstr, resolve_pos=True):
Expand Down
40 changes: 39 additions & 1 deletion tests/test_formatutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@
import re
from collections import namedtuple

import pytest
from boltons.formatutils import (get_format_args,
split_format_str,
tokenize_format_str,
infer_positional_format_args)
infer_positional_format_args,
FormatArgs,
NamedFormatArg,
PositionalFormatArg)


PFAT = namedtuple("PositionalFormatArgTest", "fstr arg_vals res")
Expand Down Expand Up @@ -48,6 +52,40 @@ def test_get_fstr_args():
return results


@pytest.mark.parametrize(('sample', 'expected'), zip(_TEST_TMPLS, [
([], [('hello', str)]),
([], [('hello', str)]),
([], [('hello', str), ('width', str)]),
([], [('hello', str), ('fchar', str), ('width', str)]),
([(0, str), (1, int), (2, float)], []),
# example 6 is skipped
]))
def test_get_format_args(sample, expected):
"""Test `get_format_args` result as tuples."""
assert get_format_args(sample) == expected


@pytest.mark.parametrize(('sample', 'expected'), zip(_TEST_TMPLS, [
Copy link
Owner

Choose a reason for hiding this comment

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

hehe this inline parametrize is kind of long, just curious, is this common practice with pytest?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I assume so; the pytest docs show an example of a multi-line parametrize right at the top. There are also a few instances in the pytest tests themselves (such as in test_conftest.py, test_config.py and test_mark.py).

If I have something like this that I intend to reuse exactly as-is, rather than moving the list of samples to a separate variable, I create a new mark:

pytest.mark.get_format_samples = pytest.mark.parametrize(('sample', 'expected), ...

Copy link
Owner

Choose a reason for hiding this comment

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

Interesting, thanks!

FormatArgs([], [NamedFormatArg('hello', str)]),
FormatArgs([], [NamedFormatArg('hello', str)]),
FormatArgs([], [NamedFormatArg('hello', str),
NamedFormatArg('width', str)]),
FormatArgs([], [NamedFormatArg('hello', str),
NamedFormatArg('fchar', str),
NamedFormatArg('width', str)]),
FormatArgs([PositionalFormatArg(0, str),
PositionalFormatArg(1, int),
PositionalFormatArg(2, float)], []),
# example 6 is skipped
]))
def test_get_format_args_namedtuples(sample, expected):
"""Test `get_format_args` result as `namedtuples`."""
result = get_format_args(sample)
assert result == expected
assert result.positional == expected.positional
assert result.named == expected.named


def test_split_fstr():
results = []
for t in _TEST_TMPLS:
Expand Down