Python string.Formatter() Examples

The following are 30 code examples of string.Formatter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module string , or try the search function .
Example #1
Source File: qemu_storage.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def convert_field(self, value, conversion):
        """
        Do conversion on the resulting object.

        supported conversions:
            'b': keep the parameter only if bool(value) is True.
            'v': keep both the parameter and its corresponding value,
                 the default mode.
        """
        if value[0] is self.sentinal:
            return string.Formatter.convert_field(self, value[1], conversion)
        if conversion is None:
            conversion = "v"
        if conversion == "v":
            return "" if value[1] is None else " ".join(value)
        if conversion == "b":
            return value[0] if bool(value[1]) else ""
        raise ValueError("Unknown conversion specifier {}".format(conversion)) 
Example #2
Source File: __init__.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 6 votes vote down vote up
def format_field(self, value, format_spec):
            if hasattr(value, "__html_format__"):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, "__html__"):
                if format_spec:
                    raise ValueError(
                        "Format specifier {0} given, but {1} does not"
                        " define __html_format__. A class that defines"
                        " __html__ must define __html_format__ to work"
                        " with format specifiers.".format(format_spec, type(value))
                    )
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
Example #3
Source File: logging.py    From python-netsurv with MIT License 6 votes vote down vote up
def is_complex_format_str(node):
    """Checks if node represents a string with complex formatting specs.

    Args:
        node (astroid.node_classes.NodeNG): AST node to check
    Returns:
        bool: True if inferred string uses complex formatting, False otherwise
    """
    inferred = utils.safe_infer(node)
    if inferred is None or not isinstance(inferred.value, str):
        return True
    try:
        parsed = list(string.Formatter().parse(inferred.value))
    except ValueError:
        # This format string is invalid
        return False
    for _, _, format_spec, _ in parsed:
        if format_spec:
            return True
    return False 
Example #4
Source File: __init__.py    From planespotter with MIT License 6 votes vote down vote up
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
Example #5
Source File: __init__.py    From recruit with Apache License 2.0 6 votes vote down vote up
def format_field(self, value, format_spec):
            if hasattr(value, "__html_format__"):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, "__html__"):
                if format_spec:
                    raise ValueError(
                        "Format specifier {0} given, but {1} does not"
                        " define __html_format__. A class that defines"
                        " __html__ must define __html_format__ to work"
                        " with format specifiers.".format(format_spec, type(value))
                    )
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
Example #6
Source File: logging.py    From linter-pylama with MIT License 6 votes vote down vote up
def is_complex_format_str(node):
    """Checks if node represents a string with complex formatting specs.

    Args:
        node (astroid.node_classes.NodeNG): AST node to check
    Returns:
        bool: True if inferred string uses complex formatting, False otherwise
    """
    inferred = utils.safe_infer(node)
    if inferred is None or not isinstance(inferred.value, six.string_types):
        return True
    try:
        parsed = list(string.Formatter().parse(inferred.value))
    except ValueError:
        # This format string is invalid
        return False
    for _, _, format_spec, _ in parsed:
        if format_spec:
            return True
    return False 
Example #7
Source File: utils.py    From timesketch with Apache License 2.0 6 votes vote down vote up
def format_data_frame(dataframe, format_message_string):
    """Add a message field to a data frame using a format message string.

    Args:
        dataframe (pandas.DataFrame): the data frame containing the data.
        format_message_String (str): the format string used to generate
            a message column.
    """
    dataframe['message'] = ''

    formatter = string.Formatter()
    for literal_text, field, _, _ in formatter.parse(format_message_string):
        dataframe['message'] = dataframe['message'] + literal_text

        if field:
            dataframe['message'] = dataframe[
                'message'] + dataframe[field].astype(str) 
Example #8
Source File: tests.py    From Fragscapy with MIT License 6 votes vote down vote up
def rm_pattern(pattern):
    """Deletes all the files that match a formatting pattern."""
    # Build the args and kwargs to use '*' in the pattern
    args = list()
    kwargs = dict()
    for _, name, _, _ in string.Formatter().parse(pattern):
        if name is None:
            continue
        if name:
            kwargs[name] = '*'
        else:
            args.append('*')

    # Remove the corresponding files
    for f in glob.glob(pattern.format(*args, **kwargs)):
        os.remove(f)


# pylint: disable=too-many-instance-attributes 
Example #9
Source File: importer.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def opensearch_convert(url):
    """Convert a basic OpenSearch URL into something qutebrowser can use.

    Exceptions:
        KeyError:
            An unknown and required parameter is present in the URL. This
            usually means there's browser/addon specific functionality needed
            to build the URL (I'm looking at you and your browser, Google) that
            obviously won't be present here.
    """
    subst = {
        'searchTerms': '%s',  # for proper escaping later
        'language': '*',
        'inputEncoding': 'UTF-8',
        'outputEncoding': 'UTF-8'
    }

    # remove optional parameters (even those we don't support)
    for param in string.Formatter().parse(url):
        if param[1]:
            if param[1].endswith('?'):
                url = url.replace('{' + param[1] + '}', '')
            elif param[2] and param[2].endswith('?'):
                url = url.replace('{' + param[1] + ':' + param[2] + '}', '')
    return search_escape(url.format(**subst)).replace('%s', '{}') 
Example #10
Source File: __init__.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def format_field(self, value, format_spec):
            if hasattr(value, "__html_format__"):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, "__html__"):
                if format_spec:
                    raise ValueError(
                        "Format specifier {0} given, but {1} does not"
                        " define __html_format__. A class that defines"
                        " __html__ must define __html_format__ to work"
                        " with format specifiers.".format(format_spec, type(value))
                    )
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
Example #11
Source File: __init__.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def format_field(self, value, format_spec):
            if hasattr(value, "__html_format__"):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, "__html__"):
                if format_spec:
                    raise ValueError(
                        "Format specifier {0} given, but {1} does not"
                        " define __html_format__. A class that defines"
                        " __html__ must define __html_format__ to work"
                        " with format specifiers.".format(format_spec, type(value))
                    )
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
Example #12
Source File: utils.py    From openstacksdk with Apache License 2.0 6 votes vote down vote up
def get_string_format_keys(fmt_string, old_style=True):
    """Gets a list of required keys from a format string

    Required mostly for parsing base_path urls for required keys, which
    use the old style string formatting.
    """
    if old_style:
        class AccessSaver:
            def __init__(self):
                self.keys = []

            def __getitem__(self, key):
                self.keys.append(key)

        a = AccessSaver()
        fmt_string % a

        return a.keys
    else:
        keys = []
        for t in string.Formatter().parse(fmt_string):
            if t[1] is not None:
                keys.append(t[1])
        return keys 
Example #13
Source File: dataset.py    From typhon with MIT License 6 votes vote down vote up
def get_subdir_resolution(self):
        """Return the resolution for the subdir precision.

        Returns "year", "month", "day", or None (if there is no subdir).

        Based on parsing of self.subdir attribute.
        """
        fm = string.Formatter()
        fields = {f[1] for f in fm.parse(str(self.subdir))}
        if "day" in fields:
            return "day"
        if "month" in fields:
            if "doy" in fields:
                raise ValueError("Format string has both month and doy")
            return "month"
        if "year" in fields:
            if "doy" in fields:
                return "day"
            return "year" 
Example #14
Source File: test_string.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_check_unused_args(self):
        class CheckAllUsedFormatter(string.Formatter):
            def check_unused_args(self, used_args, args, kwargs):
                # Track which arguments actually got used
                unused_args = set(kwargs.keys())
                unused_args.update(range(0, len(args)))

                for arg in used_args:
                    unused_args.remove(arg)

                if unused_args:
                    raise ValueError("unused arguments")

        fmt = CheckAllUsedFormatter()
        self.assertEqual(fmt.format("{0}", 10), "10")
        self.assertEqual(fmt.format("{0}{i}", 10, i=100), "10100")
        self.assertEqual(fmt.format("{0}{i}{1}", 10, 20, i=100), "1010020")
        self.assertRaises(ValueError, fmt.format, "{0}{i}{1}", 10, 20, i=100, j=0)
        self.assertRaises(ValueError, fmt.format, "{0}", 10, 20)
        self.assertRaises(ValueError, fmt.format, "{0}", 10, 20, i=100)
        self.assertRaises(ValueError, fmt.format, "{i}", 10, 20, i=100) 
Example #15
Source File: logging.py    From python-netsurv with MIT License 6 votes vote down vote up
def is_complex_format_str(node):
    """Checks if node represents a string with complex formatting specs.

    Args:
        node (astroid.node_classes.NodeNG): AST node to check
    Returns:
        bool: True if inferred string uses complex formatting, False otherwise
    """
    inferred = utils.safe_infer(node)
    if inferred is None or not isinstance(inferred.value, str):
        return True
    try:
        parsed = list(string.Formatter().parse(inferred.value))
    except ValueError:
        # This format string is invalid
        return False
    for _, _, format_spec, _ in parsed:
        if format_spec:
            return True
    return False 
Example #16
Source File: test_string.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_override_get_value(self):
        class NamespaceFormatter(string.Formatter):
            def __init__(self, namespace={}):
                string.Formatter.__init__(self)
                self.namespace = namespace

            def get_value(self, key, args, kwds):
                if isinstance(key, str):
                    try:
                        # Check explicitly passed arguments first
                        return kwds[key]
                    except KeyError:
                        return self.namespace[key]
                else:
                    string.Formatter.get_value(key, args, kwds)

        fmt = NamespaceFormatter({'greeting':'hello'})
        self.assertEqual(fmt.format("{greeting}, world!"), 'hello, world!') 
Example #17
Source File: __init__.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
Example #18
Source File: test_string.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_auto_numbering(self):
        fmt = string.Formatter()
        self.assertEqual(fmt.format('foo{}{}', 'bar', 6),
                         'foo{}{}'.format('bar', 6))
        self.assertEqual(fmt.format('foo{1}{num}{1}', None, 'bar', num=6),
                         'foo{1}{num}{1}'.format(None, 'bar', num=6))
        self.assertEqual(fmt.format('{:^{}}', 'bar', 6),
                         '{:^{}}'.format('bar', 6))
        self.assertEqual(fmt.format('{:^{}} {}', 'bar', 6, 'X'),
                         '{:^{}} {}'.format('bar', 6, 'X'))
        self.assertEqual(fmt.format('{:^{pad}}{}', 'foo', 'bar', pad=6),
                         '{:^{pad}}{}'.format('foo', 'bar', pad=6))

        with self.assertRaises(ValueError):
            fmt.format('foo{1}{}', 'bar', 6)

        with self.assertRaises(ValueError):
            fmt.format('foo{}{1}', 'bar', 6) 
Example #19
Source File: convertors.py    From mplexporter with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def export_mpl_format_str_d3(self, mpl_format_str):
        prefixes = []
        suffixes = []
        before_x = True
        format_spec_for_d3 = "" 
        for literal_text, field_name, format_spec, conversion in Formatter().parse(mpl_format_str): 
            if before_x:
                prefixes.append(literal_text)
            else:
                suffixes.append(literal_text)

            if field_name == "x" and format_spec and format_spec_for_d3 and self.is_output_d3:
                raise ValueError("D3 doesn't support multiple conversions")
                
            if field_name == "x":
                before_x = False
                format_spec_for_d3 = format_spec  

        prefix = "".join(prefixes)
        suffix = "".join(suffixes)
        return {
            "format_string": format_spec_for_d3,
            "prefix": prefix,
            "suffix": suffix
        } 
Example #20
Source File: __init__.py    From pipenv with MIT License 6 votes vote down vote up
def format_field(self, value, format_spec):
            if hasattr(value, "__html_format__"):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, "__html__"):
                if format_spec:
                    raise ValueError(
                        "Format specifier {0} given, but {1} does not"
                        " define __html_format__. A class that defines"
                        " __html__ must define __html_format__ to work"
                        " with format specifiers.".format(format_spec, type(value))
                    )
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
Example #21
Source File: postgresql.py    From django-tree with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def format_sql_in_function(sql, into=None):
    kwargs = AnyArg({'USING': AnyUsingArg()})
    # TODO: Replace Formatter with sql.format(**kwargs) when dropping Python 2.
    sql = Formatter().vformat(sql, (), kwargs).replace("'", "''")
    using = kwargs.pop('USING')
    args = ', '.join([k for k in kwargs])
    if args:
        args = ', ' + args

    extra = ''
    if into is not None:
        extra += ' INTO ' + ', '.join(into)
    if using:
        extra += ' USING ' + ', '.join([a for a in using])

    return "EXECUTE format('%s'%s)%s;" % (sql, args, extra)


# TODO: Add `LIMIT 1` where appropriate to see if it optimises a bit. 
Example #22
Source File: __init__.py    From OpenXR-SDK-Source with Apache License 2.0 6 votes vote down vote up
def format_field(self, value, format_spec):
            if hasattr(value, "__html_format__"):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, "__html__"):
                if format_spec:
                    raise ValueError(
                        "Format specifier {0} given, but {1} does not"
                        " define __html_format__. A class that defines"
                        " __html__ must define __html_format__ to work"
                        " with format specifiers.".format(format_spec, type(value))
                    )
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
Example #23
Source File: __init__.py    From scylla with Apache License 2.0 6 votes vote down vote up
def format_field(self, value, format_spec):
            if hasattr(value, "__html_format__"):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, "__html__"):
                if format_spec:
                    raise ValueError(
                        "Format specifier {0} given, but {1} does not"
                        " define __html_format__. A class that defines"
                        " __html__ must define __html_format__ to work"
                        " with format specifiers.".format(format_spec, type(value))
                    )
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
Example #24
Source File: api.py    From django-rdf-io with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def resolveTemplate(template, model, obj,mode='PUBLISH') :
    from rdf_io.models import getattr_path, ConfigVar
    vals = { 'model' : model }
    #import pdb; pdb.set_trace()
    for (literal,param,repval,conv) in Formatter().parse(template) :
        if param and param != 'model' :
            if( param[0] == '_' ) :
                val = ConfigVar.getval(param[1:],mode)
                if val:
                    vals[param] = val
                else:
                    #import pdb; pdb.set_trace()
                    raise Exception( "template references unset ConfigVariable %s" % param[1:])
            else:
                try:
                    vals[param] = urllib.quote_plus( str(iter(getattr_path(obj,param)).next()) )
                except:
                    if param == 'slug'  :
                        vals[param] = obj.id
    
    try:
        return template.format(**vals)
    except KeyError as e :
        raise KeyError( 'Property %s of model %s not found when creating API URL' % (e,model)) 
Example #25
Source File: ffmpeg_pipeline.py    From video-analytics-serving with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def start(self):
        with(self._create_delete_lock):
            if (self.start_time is not None):
                return
            self._logger.debug("Starting Pipeline %s", self.identifier)
            self.request["models"] = self.models
            self._escape_source()
            self._ffmpeg_launch_string = string.Formatter().vformat(
                self.template, [], self.request)
            self._parse_ffmpeg_launch_string(self._ffmpeg_launch_string)
            self._set_properties()
            self._set_default_models()
            self._initialize_segment_recording()
            self._generate_ffmpeg_launch_args()
            self._unescape_source()
            thread = Thread(target=self._spawn, args=[self._ffmpeg_args])
            self.start_time = time.time()
            thread.start() 
Example #26
Source File: test_string.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_auto_numbering(self):
        fmt = string.Formatter()
        self.assertEqual(fmt.format('foo{}{}', 'bar', 6),
                         'foo{}{}'.format('bar', 6))
        self.assertEqual(fmt.format('foo{1}{num}{1}', None, 'bar', num=6),
                         'foo{1}{num}{1}'.format(None, 'bar', num=6))
        self.assertEqual(fmt.format('{:^{}}', 'bar', 6),
                         '{:^{}}'.format('bar', 6))
        self.assertEqual(fmt.format('{:^{}} {}', 'bar', 6, 'X'),
                         '{:^{}} {}'.format('bar', 6, 'X'))
        self.assertEqual(fmt.format('{:^{pad}}{}', 'foo', 'bar', pad=6),
                         '{:^{pad}}{}'.format('foo', 'bar', pad=6))

        with self.assertRaises(ValueError):
            fmt.format('foo{1}{}', 'bar', 6)

        with self.assertRaises(ValueError):
            fmt.format('foo{}{1}', 'bar', 6) 
Example #27
Source File: __init__.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def format_field(self, value, format_spec):
            if hasattr(value, "__html_format__"):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, "__html__"):
                if format_spec:
                    raise ValueError(
                        "Format specifier {0} given, but {1} does not"
                        " define __html_format__. A class that defines"
                        " __html__ must define __html_format__ to work"
                        " with format specifiers.".format(format_spec, type(value))
                    )
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
Example #28
Source File: __init__.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def format_field(self, value, format_spec):
            if hasattr(value, "__html_format__"):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, "__html__"):
                if format_spec:
                    raise ValueError(
                        "Format specifier {0} given, but {1} does not"
                        " define __html_format__. A class that defines"
                        " __html__ must define __html_format__ to work"
                        " with format specifiers.".format(format_spec, type(value))
                    )
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
Example #29
Source File: test_string.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_override_get_value(self):
        class NamespaceFormatter(string.Formatter):
            def __init__(self, namespace={}):
                string.Formatter.__init__(self)
                self.namespace = namespace

            def get_value(self, key, args, kwds):
                if isinstance(key, str):
                    try:
                        # Check explicitly passed arguments first
                        return kwds[key]
                    except KeyError:
                        return self.namespace[key]
                else:
                    string.Formatter.get_value(key, args, kwds)

        fmt = NamespaceFormatter({'greeting':'hello'})
        self.assertEqual(fmt.format("{greeting}, world!"), 'hello, world!') 
Example #30
Source File: test_string.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_check_unused_args(self):
        class CheckAllUsedFormatter(string.Formatter):
            def check_unused_args(self, used_args, args, kwargs):
                # Track which arguments actually got used
                unused_args = set(kwargs.keys())
                unused_args.update(range(0, len(args)))

                for arg in used_args:
                    unused_args.remove(arg)

                if unused_args:
                    raise ValueError("unused arguments")

        fmt = CheckAllUsedFormatter()
        self.assertEqual(fmt.format("{0}", 10), "10")
        self.assertEqual(fmt.format("{0}{i}", 10, i=100), "10100")
        self.assertEqual(fmt.format("{0}{i}{1}", 10, 20, i=100), "1010020")
        self.assertRaises(ValueError, fmt.format, "{0}{i}{1}", 10, 20, i=100, j=0)
        self.assertRaises(ValueError, fmt.format, "{0}", 10, 20)
        self.assertRaises(ValueError, fmt.format, "{0}", 10, 20, i=100)
        self.assertRaises(ValueError, fmt.format, "{i}", 10, 20, i=100)