Python builtins.format() Examples

The following are 30 code examples of builtins.format(). 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 builtins , or try the search function .
Example #1
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def import_module(self, module):
        '''Import a module into the evaluator.

        Note: Import only trustworthy modules! Module imports are global,
        therefore, importing a malicious module which manipulates other global
        modules could affect code behaviour outside of the Evaluator as well.

        Args:
            module (str): Python module to import.

        Raises:
            FyppFatalError: If module could not be imported.

        '''
        rootmod = module.split('.', 1)[0]
        try:
            imported = __import__(module, self._scope)
            self.define(rootmod, imported)
        except Exception as exc:
            msg = "failed to import module '{0}'".format(module)
            raise FyppFatalError(msg, cause=exc) 
Example #2
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _define_variable(self, fname, span, name, valstr):
        result = ''
        try:
            if valstr is None:
                expr = None
            else:
                expr = self._evaluate(valstr, fname, span[0])
            self._define(name, expr)
        except Exception as exc:
            msg = "exception occurred when setting variable(s) '{0}' to '{1}'"\
                .format(name, valstr)
            raise FyppFatalError(msg, fname, span, exc)
        multiline = (span[0] != span[1])
        if self._linenums and not self._diverted and multiline:
            result = linenumdir(span[1], fname)
        return result 
Example #3
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def addglobal(self, name):
        '''Define a given entity as global.

        Args:
            name (str): Name of the entity to make global.

        Raises:
            FyppFatalError: If entity name is invalid or if the current scope is
                 a local scope and entity is already defined in it.
        '''
        varnames = self._get_variable_names(name)
        for varname in varnames:
            self._check_variable_name(varname)
            if self._locals is not None:
                if varname in self._locals:
                    msg = "variable '{0}' already defined in local scope"\
                          .format(varname)
                    raise FyppFatalError(msg)
                self._globalrefs.add(varname) 
Example #4
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _get_conditional_content(self, fname, spans, conditions, contents):
        out = []
        ieval = []
        peval = []
        multiline = (spans[0][0] != spans[-1][1])
        for condition, content, span in zip(conditions, contents, spans):
            try:
                cond = bool(self._evaluate(condition, fname, span[0]))
            except Exception as exc:
                msg = "exception occurred when evaluating '{0}'"\
                      .format(condition)
                raise FyppFatalError(msg, fname, span, exc)
            if cond:
                if self._linenums and not self._diverted and multiline:
                    out.append(linenumdir(span[1], fname))
                outcont, ievalcont, pevalcont = self._render(content)
                ieval += _shiftinds(ievalcont, len(out))
                peval += pevalcont
                out += outcont
                break
        if self._linenums and not self._diverted and multiline:
            out.append(linenumdir(spans[-1][1], fname))
        return out, ieval, peval 
Example #5
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _formatted_exception(exc):
    error_header_formstr = '{file}:{line}: '
    error_body_formstr = 'error: {errormsg} [{errorclass}]'
    if not isinstance(exc, FyppError):
        return error_body_formstr.format(
            errormsg=str(exc), errorclass=exc.__class__.__name__)
    out = []
    if exc.fname is not None:
        if exc.span[1] > exc.span[0] + 1:
            line = '{0}-{1}'.format(exc.span[0] + 1, exc.span[1])
        else:
            line = '{0}'.format(exc.span[0] + 1)
        out.append(error_header_formstr.format(file=exc.fname, line=line))
    out.append(error_body_formstr.format(errormsg=exc.msg,
                                         errorclass=exc.__class__.__name__))
    if exc.cause is not None:
        out.append('\n' + _formatted_exception(exc.cause))
    out.append('\n')
    return ''.join(out) 
Example #6
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _get_eval(self, fname, span, expr):
        try:
            result = self._evaluate(expr, fname, span[0])
        except Exception as exc:
            msg = "exception occurred when evaluating '{0}'".format(expr)
            raise FyppFatalError(msg, fname, span, exc)
        out = []
        ieval = []
        peval = []
        if result is not None:
            out.append(str(result))
            if not self._diverted:
                ieval.append(0)
                peval.append((span, fname))
        if span[0] != span[1]:
            out.append('\n')
        return out, ieval, peval 
Example #7
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _get_callable_argspec_py3(func):
    sig = inspect.signature(func)
    args = []
    defaults = {}
    varpos = None
    varkw = None
    for param in sig.parameters.values():
        if param.kind == param.POSITIONAL_OR_KEYWORD:
            args.append(param.name)
            if param.default != param.empty:
                defaults[param.name] = param.default
        elif param.kind == param.VAR_POSITIONAL:
            varpos = param.name
        elif param.kind == param.VAR_KEYWORD:
            varkw = param.name
        else:
            msg = "argument '{0}' has invalid argument type".format(param.name)
            raise FyppFatalError(msg)
    return args, defaults, varpos, varkw


# Signature objects are available from Python 3.3 (and deprecated from 3.5) 
Example #8
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _open_output_file(outfile, encoding=None, create_parents=False):
    if create_parents:
        parentdir = os.path.abspath(os.path.dirname(outfile))
        if not os.path.exists(parentdir):
            try:
                os.makedirs(parentdir)
            except OSError as exc:
                if exc.errno != errno.EEXIST:
                    msg = "Folder '{0}' can not be created"\
                        .format(parentdir)
                    raise FyppFatalError(msg, cause=exc)
    try:
        outfp = io.open(outfile, 'w', encoding=encoding)
    except IOError as exc:
        msg = "Failed to open file '{0}' for write".format(outfile)
        raise FyppFatalError(msg, cause=exc)
    return outfp 
Example #9
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, maxlen=132, indent=4, method='smart', prefix='&',
                 suffix='&'):
        # Line length should be long enough that contintuation lines can host at
        # east one character apart of indentation and two continuation signs
        minmaxlen = indent + len(prefix) + len(suffix) + 1
        if maxlen < minmaxlen:
            msg = 'Maximal line length less than {0} when using an indentation'\
                  ' of {1}'.format(minmaxlen, indent)
            raise FyppFatalError(msg)
        self._maxlen = maxlen
        self._indent = indent
        self._prefix = ' ' * self._indent + prefix
        self._suffix = suffix
        if method not in ['brute', 'smart', 'simple']:
            raise FyppFatalError('invalid folding type')
        if method == 'brute':
            self._inherit_indent = False
            self._fold_position_finder = self._get_maximal_fold_pos
        elif method == 'simple':
            self._inherit_indent = True
            self._fold_position_finder = self._get_maximal_fold_pos
        elif method == 'smart':
            self._inherit_indent = True
            self._fold_position_finder = self._get_smart_fold_pos 
Example #10
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _check_if_matches_last(self, lastdir, curdir, lastspan, curspan,
                               directive):
        if curdir != lastdir:
            msg = "mismatching '{0}' directive (last block opened was '{1}')"\
                .format(directive, lastdir)
            raise FyppFatalError(msg, self._curfile, curspan)
        inline_last = lastspan[0] == lastspan[1]
        inline_cur = curspan[0] == curspan[1]
        if inline_last != inline_cur:
            if inline_cur:
                msg = 'expecting line form of directive {0}'.format(directive)
            else:
                msg = 'expecting inline form of directive {0}'.format(directive)
            raise FyppFatalError(msg, self._curfile, curspan)
        elif inline_cur and curspan[0] != lastspan[0]:
            msg = 'inline directives of the same construct must be in the '\
                  'same row'
            raise FyppFatalError(msg, self._curfile, curspan) 
Example #11
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def handle_enddef(self, span, name):
        '''Should be called to signalize an enddef directive.

        Args:
            span (tuple of int): Start and end line of the directive.
            name (str): Name of the enddef statement. Could be None, if enddef
                was specified without name.
        '''
        self._check_for_open_block(span, 'enddef')
        block = self._open_blocks.pop(-1)
        directive, fname, spans = block[0:3]
        self._check_if_matches_last(directive, 'def', spans[-1], span, 'enddef')
        defname, argexpr, dummy = block[3:6]
        if name is not None and name != defname:
            msg = "wrong name in enddef directive "\
                  "(expected '{0}', got '{1}')".format(defname, name)
            raise FyppFatalError(msg, fname, span)
        spans.append(span)
        block = (directive, fname, spans, defname, argexpr, self._curnode)
        self._curnode = self._path.pop(-1)
        self._curnode.append(block) 
Example #12
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _handle_assert(self, fname, span, expr):
        result = ''
        try:
            cond = bool(self._evaluate(expr, fname, span[0]))
        except Exception as exc:
            msg = "exception occurred when evaluating assert condition '{0}'"\
                .format(expr)
            raise FyppFatalError(msg, fname, span, exc)
        if not cond:
            msg = "Assertion failed ('{0}')".format(expr)
            raise FyppStopRequest(msg, fname, span)
        if self._linenums and not self._diverted:
            result = linenumdir(span[1], fname)
        return result 
Example #13
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _delete_variable(self, fname, span, name):
        result = ''
        try:
            self._evaluator.undefine(name)
        except Exception as exc:
            msg = "exception occurred when deleting variable(s) '{0}'"\
                  .format(name)
            raise FyppFatalError(msg, fname, span, exc)
        multiline = (span[0] != span[1])
        if self._linenums and not self._diverted and multiline:
            result = linenumdir(span[1], fname)
        return result 
Example #14
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def undefine(self, name):
        '''Undefine a Python entity.

        Args:
            name (str): Name of the entity to undefine.

        Raises:
            FyppFatalError: If name starts with the reserved prefix or if it is
                a reserved name.
        '''
        varnames = self._get_variable_names(name)
        for varname in varnames:
            self._check_variable_name(varname)
            deleted = False
            if self._locals is None:
                if varname in self._globals:
                    del self._globals[varname]
                    deleted = True
            else:
                if varname in self._locals:
                    del self._locals[varname]
                    del self._scope[varname]
                    deleted = True
                elif varname in self._globalrefs and varname in self._globals:
                    del self._globals[varname]
                    del self._scope[varname]
                    deleted = True
            if not deleted:
                msg = "lookup for an erasable instance of '{0}' failed"\
                      .format(varname)
                raise FyppFatalError(msg) 
Example #15
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _get_variable_names(varexpr):
        lpar = varexpr.startswith('(')
        rpar = varexpr.endswith(')')
        if lpar != rpar:
            msg = "unbalanced parenthesis around variable varexpr(s) in '{0}'"\
                .format(varexpr)
            raise FyppFatalError(msg, None, None)
        if lpar:
            varexpr = varexpr[1:-1]
        varnames = [s.strip() for s in varexpr.split(',')]
        return varnames 
Example #16
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _func_import(self, name, *_, **__):
        module = self._scope.get(name, None)
        if module is not None and isinstance(module, types.ModuleType):
            return module
        msg = "Import of module '{0}' via '__import__' not allowed".format(name)
        raise ImportError(msg) 
Example #17
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _process_arguments(self, args, keywords):
        kwdict = dict(keywords)
        argdict = {}
        nargs = min(len(args), len(self._argnames))
        for iarg in range(nargs):
            argdict[self._argnames[iarg]] = args[iarg]
        if nargs < len(args):
            if self._varpos is None:
                msg = "macro '{0}' called with too many positional arguments "\
                      "(expected: {1}, received: {2})"\
                      .format(self._name, len(self._argnames), len(args))
                raise FyppFatalError(msg, self._fname, self._spans[0])
            else:
                argdict[self._varpos] = list(args[nargs:])
        elif self._varpos is not None:
            argdict[self._varpos] = []
        for argname in self._argnames[:nargs]:
            if argname in kwdict:
                msg = "got multiple values for argument '{0}'".format(argname)
                raise FyppFatalError(msg, self._fname, self._spans[0])
        if nargs < len(self._argnames):
            for argname in self._argnames[nargs:]:
                if argname in kwdict:
                    argdict[argname] = kwdict.pop(argname)
                elif argname in self._defaults:
                    argdict[argname] = self._defaults[argname]
                else:
                    msg = "macro '{0}' called without mandatory positional "\
                          "argument '{1}'".format(self._name, argname)
                    raise FyppFatalError(msg, self._fname, self._spans[0])
        if kwdict and self._varkw is None:
            kwstr = "', '".join(kwdict.keys())
            msg = "macro '{0}' called with unknown keyword argument(s) '{1}'"\
                  .format(self._name, kwstr)
            raise FyppFatalError(msg, self._fname, self._spans[0])
        if self._varkw is not None:
            argdict[self._varkw] = kwdict
        return argdict 
Example #18
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _apply_definitions(defines, evaluator):
        for define in defines:
            words = define.split('=', 2)
            name = words[0]
            value = None
            if len(words) > 1:
                try:
                    value = evaluator.evaluate(words[1])
                except Exception as exc:
                    msg = "exception at evaluating '{0}' in definition for " \
                          "'{1}'".format(words[1], name)
                    raise FyppFatalError(msg, cause=exc)
            evaluator.define(name, value) 
Example #19
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def linenumdir(linenr, fname, flag=None):
    '''Returns a line numbering directive.

    Args:
        linenr (int): Line nr (starting with 0).
        fname (str): File name.
    '''
    if flag is None:
        return '# {0} "{1}"\n'.format(linenr + 1, fname)
    return '# {0} "{1}" {2}\n'.format(linenr + 1, fname, flag) 
Example #20
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _argsplit_fortran(argtxt):
    txt = _INLINE_EVAL_REGION_REGEXP.sub(_blank_match, argtxt)
    splitpos = [-1]
    quote = None
    closing_brace_stack = []
    closing_brace = None
    for ind, char in enumerate(txt):
        if quote:
            if char == quote:
                quote = None
            continue
        if char in _QUOTES_FORTRAN:
            quote = char
            continue
        if char in _OPENING_BRACKETS_FORTRAN:
            closing_brace_stack.append(closing_brace)
            ind = _OPENING_BRACKETS_FORTRAN.index(char)
            closing_brace = _CLOSING_BRACKETS_FORTRAN[ind]
            continue
        if char in _CLOSING_BRACKETS_FORTRAN:
            if char == closing_brace:
                closing_brace = closing_brace_stack.pop(-1)
                continue
            else:
                msg = "unexpected closing delimiter '{0}' in expression '{1}' "\
                      "at position {2}".format(char, argtxt, ind + 1)
                raise FyppFatalError(msg)
        if not closing_brace and char == _ARGUMENT_SPLIT_CHAR_FORTRAN:
            splitpos.append(ind)
    if quote or closing_brace:
        msg = "open quotes or brackets in expression '{0}'".format(argtxt)
        raise FyppFatalError(msg)
    splitpos.append(len(txt))
    fragments = [argtxt[start + 1 : end]
                 for start, end in zip(splitpos, splitpos[1:])]
    return fragments 
Example #21
Source File: _logger.py    From loguru with MIT License 5 votes vote down vote up
def bind(__self, **kwargs):
        """Bind attributes to the ``extra`` dict of each logged message record.

        This is used to add custom context to each logging call.

        Parameters
        ----------
        **kwargs
            Mapping between keys and values that will be added to the ``extra`` dict.

        Returns
        -------
        :class:`~Logger`
            A logger wrapping the core logger, but which sends record with the customized ``extra``
            dict.

        Examples
        --------
        >>> logger.add(sys.stderr, format="{extra[ip]} - {message}")
        >>> class Server:
        ...     def __init__(self, ip):
        ...         self.ip = ip
        ...         self.logger = logger.bind(ip=ip)
        ...     def call(self, message):
        ...         self.logger.info(message)
        ...
        >>> instance_1 = Server("192.168.0.200")
        >>> instance_2 = Server("127.0.0.1")
        >>> instance_1.call("First instance")
        192.168.0.200 - First instance
        >>> instance_2.call("Second instance")
        127.0.0.1 - Second instance
        """
        *options, extra = __self._options
        return Logger(__self._core, *options, {**extra, **kwargs}) 
Example #22
Source File: _logger.py    From loguru with MIT License 5 votes vote down vote up
def trace(__self, __message, *args, **kwargs):
        r"""Log ``message.format(*args, **kwargs)`` with severity ``'TRACE'``."""
        __self._log("TRACE", None, False, __self._options, __message, args, kwargs) 
Example #23
Source File: _logger.py    From loguru with MIT License 5 votes vote down vote up
def info(__self, __message, *args, **kwargs):
        r"""Log ``message.format(*args, **kwargs)`` with severity ``'INFO'``."""
        __self._log("INFO", None, False, __self._options, __message, args, kwargs) 
Example #24
Source File: _logger.py    From loguru with MIT License 5 votes vote down vote up
def success(__self, __message, *args, **kwargs):
        r"""Log ``message.format(*args, **kwargs)`` with severity ``'SUCCESS'``."""
        __self._log("SUCCESS", None, False, __self._options, __message, args, kwargs) 
Example #25
Source File: _logger.py    From loguru with MIT License 5 votes vote down vote up
def warning(__self, __message, *args, **kwargs):
        r"""Log ``message.format(*args, **kwargs)`` with severity ``'WARNING'``."""
        __self._log("WARNING", None, False, __self._options, __message, args, kwargs) 
Example #26
Source File: _logger.py    From loguru with MIT License 5 votes vote down vote up
def error(__self, __message, *args, **kwargs):
        r"""Log ``message.format(*args, **kwargs)`` with severity ``'ERROR'``."""
        __self._log("ERROR", None, False, __self._options, __message, args, kwargs) 
Example #27
Source File: _logger.py    From loguru with MIT License 5 votes vote down vote up
def critical(__self, __message, *args, **kwargs):
        r"""Log ``message.format(*args, **kwargs)`` with severity ``'CRITICAL'``."""
        __self._log("CRITICAL", None, False, __self._options, __message, args, kwargs) 
Example #28
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _process_call(self, param, span, blockcall):
        match = _SIMPLE_CALLABLE_REGEXP.match(param)
        if not match:
            msg = "invalid callable expression '{}'".format(param)
            raise FyppFatalError(msg, self._curfile, span)
        name, args = match.groups()
        self.handle_call(span, name, args, blockcall) 
Example #29
Source File: extraction.py    From PyPCAPKit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def output(self):
        """Name of output file.

        Raises:
            UnsupportedCall: If :attr:`self._flag_q <pcapkit.foundation.extraction.Extractor._flag_q>`
                is set as :data:`True`, as output is disabled by initialisation parameter.

        :rtype: str
        """
        if self._flag_q:
            raise UnsupportedCall("'Extractor(nofile=True)' object has no attribute 'format'")
        return self._ofnm 
Example #30
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __str__(self):
        msg = [self.__class__.__name__, ': ']
        if self.fname is not None:
            msg.append("file '" + self.fname + "'")
            if self.span[1] > self.span[0] + 1:
                msg.append(', lines {0}-{1}'.format(
                    self.span[0] + 1, self.span[1]))
            else:
                msg.append(', line {0}'.format(self.span[0] + 1))
            msg.append('\n')
        if self.msg:
            msg.append(self.msg)
        if self.cause is not None:
            msg.append('\n' + str(self.cause))
        return ''.join(msg)