o
    Pεi*                     @   s   d Z ddlZddlZddlZddlZeeeeeeje	ej
eeejejeeiZG dd deZG dd deeZG dd deZG d	d
 d
eZG dd deZdddZdS )z
jsonlines implementation
    Nc                   @   s   e Zd ZdZdS )ErrorzBase error class.N)__name__
__module____qualname____doc__ r   r   G/home/ubuntu/.local/lib/python3.10/site-packages/jsonlines/jsonlines.pyr      s    r   c                       s(   e Zd ZdZdZdZ fddZ  ZS )InvalidLineErrora  
    Error raised when an invalid line is encountered.

    This happens when the line does not contain valid JSON, or if a
    specific data type has been requested, and the line contained a
    different data type.

    The original line itself is stored on the exception instance as the
    ``.line`` attribute, and the line number as ``.lineno``.

    This class subclasses both ``jsonlines.Error`` and the built-in
    ``ValueError``.
    Nc                    s0   d ||}| | _|| _tt| | d S )Nz{} (line {}))formatrstriplinelinenosuperr	   __init__)selfmsgr   r   	__class__r   r   r   0   s   
zInvalidLineError.__init__)r   r   r   r   r   r   r   __classcell__r   r   r   r   r	      s
    r	   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )ReaderWriterBasezJ
    Base class with shared behaviour for both the reader and writer.
    c                 C   s(   | j rdS d| _ | jr| j  dS dS )z
        Close this reader/writer.

        This closes the underlying file if that file has been opened by
        this reader/writer. When an already opened file-like object was
        provided, the caller is responsible for closing it.
        NT)_closed_should_close_fp_fpcloser   r   r   r   r   ;   s   zReaderWriterBase.closec                 C   sN   t | jdd }|rt|}ndt| jjt| j}dt| jt| |S )Nnamez<{} at 0x{:x}>z$<jsonlines.{} at 0x{:x} wrapping {}>)getattrr   reprr
   typer   id)r   r   wrappingr   r   r   __repr__I   s   

zReaderWriterBase.__repr__c                 C   s   | S Nr   r   r   r   r   	__enter__T   s   zReaderWriterBase.__enter__c                 G   s   |    dS )NF)r   )r   exc_infor   r   r   __exit__W   s   zReaderWriterBase.__exit__N)r   r   r   r   r   r!   r#   r%   r   r   r   r   r   7   s    r   c                   @   s:   e Zd ZdZdddZdddZ		ddd	Zd
d ZdS )Readera  
    Reader for the jsonlines format.

    The first argument must be an iterable that yields JSON encoded
    strings. Usually this will be a readable file-like object, such as
    an open file or an ``io.TextIO`` instance, but it can also be
    something else as long as it yields strings when iterated over.

    The `loads` argument can be used to replace the standard json
    decoder. If specified, it must be a callable that accepts a
    (unicode) string and returns the decoded object.

    Instances are iterable and can be used as a context manager.

    :param file-like iterable: iterable yielding lines as strings
    :param callable loads: custom json decoder callable
    Nc                 C   s6   || _ d| _d| _|d u rtj}|| _t|d| _d S )NF   )r   r   r   jsonloads_loads	enumerate
_line_iter)r   iterabler)   r   r   r   r   n   s   zReader.__init__Fc           
   
   C   s  | j rtd|dur|tvrtdzt| j\}}|r.| s.t| j\}}|r.| r!W n ty>   t	t
d Y nw t|tjrnz|d}W n! tym } ztd|||}t	|| W Y d}~nd}~ww z| |}W n! ty } ztd|||}t	|| W Y d}~nd}~ww |du r|rdS td|||durt|t| }	|ttjfv r|	ot|t }	|	std|||S )	a  
        Read and decode a line.

        The optional `type` argument specifies the expected data type.
        Supported types are ``dict``, ``list``, ``str``, ``int``,
        ``float``, ``numbers.Number`` (accepts both integers and
        floats), and ``bool``. When specified, non-conforming lines
        result in :py:exc:`InvalidLineError`.

        By default, input lines containing ``null`` (in JSON) are
        considered invalid, and will cause :py:exc:`InvalidLineError`.
        The `allow_none` argument can be used to change this behaviour,
        in which case ``None`` will be returned instead.

        If `skip_empty` is set to ``True``, empty lines and lines
        containing only whitespace are silently skipped.
        zreader is closedNzinvalid type specifiedutf-8zline is not valid utf-8: {}zline contains invalid json: {}zline contains null valuez"line does not match requested type)r   RuntimeErrorTYPE_MAPPING
ValueErrornextr,   r   StopIterationsix
raise_fromEOFError
isinstancebinary_typedecodeUnicodeDecodeErrorr	   r
   r*   intnumbersNumberbool)
r   r   
allow_none
skip_emptyr   r   orig_excexcvaluevalidr   r   r   readw   sb   zReader.readc                 c   sL    z	 z| j |||dV  W n ty   |s Y nw q ty%   Y dS w )a  
        Iterate over all lines.

        This is the iterator equivalent to repeatedly calling
        :py:meth:`~Reader.read()`. If no arguments are specified, this
        is the same as directly iterating over this :py:class:`Reader`
        instance.

        When `skip_invalid` is set to ``True``, invalid lines will be
        silently ignored.

        See :py:meth:`~Reader.read()` for a description of the other
        arguments.
        T)r   r?   r@   N)rE   r	   r6   )r   r   r?   r@   skip_invalidr   r   r   iter   s$   	zReader.iterc                 C   s   |   S )z0
        See :py:meth:`~Reader.iter()`.
        )rG   r   r   r   r   __iter__   s   zReader.__iter__r"   )NFF)NFFF)r   r   r   r   r   rE   rG   rH   r   r   r   r   r&   \   s    

	?
r&   c                   @   s,   e Zd ZdZ	d
ddZdd Zdd	 ZdS )Writera  
    Writer for the jsonlines format.

    The `fp` argument must be a file-like object with a ``.write()``
    method accepting either text (unicode) or bytes.

    The `compact` argument can be used to to produce smaller output.

    The `sort_keys` argument can be used to sort keys in json objects,
    and will produce deterministic output.

    For more control, provide a a custom encoder callable using the
    `dumps` argument. The callable must produce (unicode) string output.
    If specified, the `compact` and `sort` arguments will be ignored.

    When the `flush` argument is set to ``True``, the writer will call
    ``fp.flush()`` after each written line.

    Instances can be used as a context manager.

    :param file-like fp: writable file-like object
    :param bool compact: whether to use a compact output format
    :param bool sort_keys: whether to sort object keys
    :param callable dumps: custom encoder callable
    :param bool flush: whether to flush the file-like object after
        writing each line
    FNc                 C   s   d| _ z
|d d| _W n ty   d| _Y nw |d u r5td|d}|r,|jdd tjdi |j}|| _	d| _
|| _|| _d S )NF T)ensure_ascii	sort_keys),:)
separatorsr   )r   write_fp_is_binary	TypeErrordictupdater(   JSONEncoderencoder   r   _dumps_flush)r   fpcompactrL   dumpsflushencoder_kwargsr   r   r   r      s    



zWriter.__init__c                 C   s   | j rtd| |}| jr't|tjs|d}| j	| | j	d nt|tj
s2|d}| j	| | j	d | jrH| j  dS dS )zg
        Encode and write a single object.

        :param obj: the object to encode and write
        zwriter is closedr.      
ascii
N)r   r/   rW   rQ   r7   r4   r8   rV   r   rP   	text_typer9   rX   r\   )r   objr   r   r   r   rP     s   


zWriter.writec                 C   s   |D ]}|  | qdS )ze
        Encode and write multiple objects.

        :param iterable: an iterable of objects
        N)rP   )r   r-   rb   r   r   r   	write_all"  s   zWriter.write_all)FFNF)r   r   r   r   r   rP   rc   r   r   r   r   rI      s    
rI   rc                 K   sX   |dvrt dtj| |d dd}|dkrt|fi |}nt|fi |}d|_|S )a  
    Open a jsonlines file for reading or writing.

    This is a convenience function that opens a file, and wraps it in
    either a :py:class:`Reader` or :py:class:`Writer` instance,
    depending on the specified `mode`.

    Any additional keyword arguments will be passed on to the reader and
    writer: see their documentation for available options.

    The resulting reader or writer must be closed after use by the
    caller, which will also close the opened file.  This can be done by
    calling ``.close()``, but the easiest way to ensure proper resource
    finalisation is to use a ``with`` block (context manager), e.g.

    ::

        with jsonlines.open('out.jsonl', mode='w') as writer:
            writer.write(...)

    :param file-like fp: name of the file to open
    :param str mode: whether to open the file for reading (``r``),
        writing (``w``) or appending (``a``).
    :param \*\*kwargs: additional arguments, forwarded to the reader or writer
    >   ard   wz&'mode' must be either 'r', 'w', or 'a'tr.   )modeencodingrd   T)r1   ioopenr&   rI   r   )r   rh   kwargsrY   instancer   r   r   rk   ,  s   rk   )rd   )r   r<   rj   r(   r4   rS   liststrra   r;   integer_typesfloatr=   r>   r0   	Exceptionr   r1   r	   objectr   r&   rI   rk   r   r   r   r   <module>   s&    %~R