
    .Ph1                        d Z ddlZddlmZ g dZ ej        d          Zd Zd Zd Z	d	Z
d
Z ed e
D             d eD             z             Zeed<   d ZddZ G d d          Z e            Z G d d          ZdS )aG  `PEP 3101`_ introduced the :meth:`str.format` method, and what
would later be called "new-style" string formatting. For the sake of
explicit correctness, it is probably best to refer to Python's dual
string formatting capabilities as *bracket-style* and
*percent-style*. There is overlap, but one does not replace the
other.

  * Bracket-style is more pluggable, slower, and uses a method.
  * Percent-style is simpler, faster, and uses an operator.

Bracket-style formatting brought with it a much more powerful toolbox,
but it was far from a full one. :meth:`str.format` uses `more powerful
syntax`_, but `the tools and idioms`_ for working with
that syntax are not well-developed nor well-advertised.

``formatutils`` adds several functions for working with bracket-style
format strings:

  * :class:`DeferredValue`: Defer fetching or calculating a value
    until format time.
  * :func:`get_format_args`: Parse the positional and keyword
    arguments out of a format string.
  * :func:`tokenize_format_str`: Tokenize a format string into
    literals and :class:`BaseFormatField` objects.
  * :func:`construct_format_field_str`: Assists in programmatic
    construction of format strings.
  * :func:`infer_positional_format_args`: Converts anonymous
    references in 2.7+ format strings to explicit positional arguments
    suitable for usage with Python 2.6.

.. _more powerful syntax: https://docs.python.org/2/library/string.html#format-string-syntax
.. _the tools and idioms: https://docs.python.org/2/library/string.html#string-formatting
.. _PEP 3101: https://www.python.org/dev/peps/pep-3101/
    N)	Formatter)DeferredValueget_format_argstokenize_format_strconstruct_format_field_strinfer_positional_format_argsBaseFormatFieldz({{)|(}})|({[:!.\[}])c                 J    | dS d| z   }|r|d|z   z  }|r|d|z   z  }|dz  }|S )z
    Constructs a format field string from the field name, spec, and
    conversion character (``fname``, ``fspec``, ``conv``). See Python
    String Formatting for more info.
    N {!:} )fnamefspecconvrets       S/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/boltons/formatutils.pyr   r   R   sQ     }r
+C sTz sU{3JCJ    c                     g }t                                          |           D ]I\  }}}}||                    |df           !t          |||          }|                    ||f           J|S )zDoes very basic splitting of a format string, returns a list of
    strings. For full tokenization, see :func:`tokenize_format_str`.

    N)r   parseappendr   )fstrr   litr   r   r   	field_strs          r   split_format_strr   c   s    
 C#,;;#4#4T#:#: % %UE4=JJT{###.ueTBB	

C#$$$$Jr   c                 d   d\  }}d\  }}}t                               |           D ]|}|                                |                                |                                }}}||k     r|| ||         z  }|}|dk    s|dk    r||z  }e|d| |dd          z  }|dz  }}|| |d         z  }|S )zTakes format strings with anonymous positional arguments, (e.g.,
    "{}" and {:d}), and converts them into numbered ones for explicitness and
    compatibility with 2.6.

    Returns a string with the inferred positional arguments.
    )r   r   )r   r   r   z{{z}}r      N)_pos_farg_refinditerstartendgroup)r   r   max_anonr"   r#   prev_endmatchr$   s           r   r   r   s   s     MC"E3&&t,, 	 	!KKMM599;;Ese4''CD==ETMM5LC)H)eABBi)))A4		?CJr   bcdoxXnzeEfFgGn%c                      g | ]}|t           fS r   )int.0xs     r   
<listcomp>r.      s    ...q1c(...r   c                      g | ]}|t           fS r   )floatr+   s     r   r.   r.      s    2221e*222r   sc                    t                      }g g t                      cd
fd	}|                    |           D ]\  }}}}||dd         }t          j        d|          }t          |          dk    rt          d|z            	 |d         }	|	sJ n$# t          t          f$ r t          d	          w xY w |||           |                    |          D ]\  }
}}}| ||           fS )a  
    Turn a format string into two lists of arguments referenced by the
    format string. One is positional arguments, and the other is named
    arguments. Each element of the list includes the name and the
    nominal type of the field.

    # >>> get_format_args("{noun} is {1:d} years old{punct}")
    # ([(1, <type 'int'>)], [('noun', <type 'str'>), ('punct', <type 'str'>)])

    # XXX: Py3k
    >>> get_format_args("{noun} is {1:d} years old{punct}") ==         ([(1, int)], [('noun', str), ('punct', str)])
    True
    r1   c                    | vr                     |            t                              |t                    }	                     t          |           |f           d S # t          $ r                     | |f           Y d S w xY wd S N)add	_TYPE_MAPgetstrr   r*   
ValueError)argname	type_charargtype_dedupfargsfkwargss      r   _add_argz!get_format_args.<locals>._add_arg   s    &  JJwmmIs33G3c'llG455555 3 3 312222223 ! s   $A" "!BBN[.[]r   z#encountered compound format arg: %rr   z)encountered anonymous positional argument)r1   )	r   setr   resplitlenr9   
IndexErrorAssertionError)r   	formatterr@   r   r   r   r   r;   
fname_list
base_fnamesublitsubfname_r=   r>   r?   s                @@@r   r   r      sd     ISUUE7F3 3 3 3 3 3 3 3 $-??4#8#8 ' 'UE4bcc
I&%00J:"" !F!NOOON']
!!!!!/ N N N !LMMMNHUI&&&*3//%*@*@ ' '&!Q'HX&&&'>s   B!B>Tc                     g }|rt          |           } t                      }|                    |           D ]E\  }}}}|r|                    |           |!|                    t	          |||                     F|S )a$  Takes a format string, turns it into a list of alternating string
    literals and :class:`BaseFormatField` tokens. By default, also
    infers anonymous positional references into explicit, numbered
    positional references. To disable this behavior set *resolve_pos*
    to ``False``.
    )r   r   r   r   r	   )r   resolve_posr   rI   r   r   r   r   s           r   r   r      s     C 2+D11I#,??4#8#8 8 8UE4 	JJsOOO=

?5%667777Jr   c                   N    e Zd ZdZddZd Zd Zd Zed             Z	d	 Z
d
 ZdS )r	   a  A class representing a reference to an argument inside of a
    bracket-style format string. For instance, in ``"{greeting},
    world!"``, there is a field named "greeting".

    These fields can have many options applied to them. See the
    Python docs on `Format String Syntax`_ for the full details.

    .. _Format String Syntax: https://docs.python.org/2/library/string.html#string-formatting
    r   Nc                     |                      |           |                     |           |                     |           d S r4   )	set_fname	set_fspecset_conv)selfr   r   r   s       r   __init__zBaseFormatField.__init__   s>    uudr   c                     t          j        d|          }|d         | _        || _        |dd         | _        | j         p| j                                        | _        dS )zSet the field name.rB   r   r   N)rD   rE   	base_namer   subpathisdigitis_positional)rV   r   	path_lists      r   rS   zBaseFormatField.set_fname   s\     HVU++	"1
 }!%/K4>3I3I3K3Kr   c                     |pd}g }t                                          |          D ]\  }}}}||                    |           || _        || _        |dd         | _        t                              | j        t                    | _	        dS )zSet the field spec.r   NrA   )
r   r   r   	subfieldsr   r;   r6   r7   r8   	type_func)rV   r   r_   rL   rM   rN   s         r   rT   zBaseFormatField.set_fspec   s    	&/kk&7&7&>&> 	+ 	+"FHa#  ***"
rss"t~s;;r   c                 "    || _         d| _        dS )zuThere are only two built-in converters: ``s`` and ``r``. They are
        somewhat rare and appearlike ``"{ref!r}"``.N)r   	conv_func)rV   r   s     r   rU   zBaseFormatField.set_conv   s     	r   c                 B    t          | j        | j        | j                  S )z0The current state of the field in string format.)r   r   r   r   rV   s    r   r   zBaseFormatField.fstr  s     *$*dj$)LLLr   c                    | j         j        }| j        g}| j        "|                    | j        | j        g           n%| j        dk    r|                    | j                   d                    d |D                       }| d| dS )Nr   z, c                 ,    g | ]}t          |          S r   )repr)r,   as     r   r.   z,BaseFormatField.__repr__.<locals>.<listcomp>  s    5551tAww555r   ())	__class____name__r   r   extendr   r   join)rV   cnargs	args_reprs       r   __repr__zBaseFormatField.__repr__  s    ^$
|9 KKTY/0000Z2KK
###II5555566	##y####r   c                     | j         S r4   )r   rd   s    r   __str__zBaseFormatField.__str__  s
    yr   )r   N)rl   
__module____qualname____doc__rW   rS   rT   rU   propertyr   rr   rt   r   r   r   r	   r	      s            
L L L
< 
< 
<   M M XM$ $ $    r   r	   c                   D    e Zd ZdZddZd Zd Zd Zd Zd Z	d	 Z
d
 ZdS )r   a  :class:`DeferredValue` is a wrapper type, used to defer computing
    values which would otherwise be expensive to stringify and
    format. This is most valuable in areas like logging, where one
    would not want to waste time formatting a value for a log message
    which will subsequently be filtered because the message's log
    level was DEBUG and the logger was set to only emit CRITICAL
    messages.

    The :class:``DeferredValue`` is initialized with a callable that
    takes no arguments and returns the value, which can be of any
    type. By default DeferredValue only calls that callable once, and
    future references will get a cached value. This behavior can be
    disabled by setting *cache_value* to ``False``.

    Args:

        func (function): A callable that takes no arguments and
            computes the value being represented.
        cache_value (bool): Whether subsequent usages will call *func*
            again. Defaults to ``True``.

    >>> import sys
    >>> dv = DeferredValue(lambda: len(sys._current_frames()))
    >>> output = "works great in all {0} threads!".format(dv)

    PROTIP: To keep lines shorter, use: ``from formatutils import
    DeferredValue as DV``
    Tc                 :    || _         || _        t          | _        d S r4   )funccache_value_UNSET_value)rV   r{   r|   s      r   rW   zDeferredValue.__init__6  s    	&r   c                     | j         t          ur| j        r| j         }n"|                                 }| j        r|| _         |S )zComputes, optionally caches, and returns the value of the
        *func*. If ``get_value()`` has been called before, a cached
        value may be returned depending on the *cache_value* option
        passed to the constructor.
        )r~   r}   r|   r{   )rV   values     r   	get_valuezDeferredValue.get_value;  sF     ;f$$)9$KEEIIKKE $#r   c                 D    t          |                                           S r4   )r*   r   rd   s    r   __int__zDeferredValue.__int__I      4>>##$$$r   c                 D    t          |                                           S r4   )r0   r   rd   s    r   	__float__zDeferredValue.__float__L  s    T^^%%&&&r   c                 D    t          |                                           S r4   r8   r   rd   s    r   rt   zDeferredValue.__str__O  r   r   c                 D    t          |                                           S r4   r   rd   s    r   __unicode__zDeferredValue.__unicode__R  r   r   c                 D    t          |                                           S r4   )rg   r   rd   s    r   rr   zDeferredValue.__repr__U  s    DNN$$%%%r   c                    |                                  }|dd          }t                              |t                    }	 |                    |          S # t
          t          f$ r!  ||                              |          cY S w xY w)NrA   )r   r6   r7   r8   
__format__r9   	TypeError)rV   fmtr   pt	type_convs        r   r   zDeferredValue.__format__X  s      XMM"c**		4##C(((I& 	4 	4 	49U##..s33333	4s    A /BBNT)rl   ru   rv   rw   rW   r   r   r   rt   r   rr   r   r   r   r   r   r     s         8   
  % % %' ' '% % %% % %& & &
4 
4 
4 
4 
4r   r   r   )rw   rD   stringr   __all__compiler    r   r   r   	_INTCHARS_FLOATCHARSdictr6   r8   r   r   r	   objectr}   r   r   r   r   <module>r      sh  >! !L 
			        
 rz ) * *
  "     4 	D..I...22k2223 4 4		#, , ,^   (< < < < < < < <~ 
I4 I4 I4 I4 I4 I4 I4 I4 I4 I4r   