U
    aJ                     @   s0  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZ ejdkrddl	mZ nddlmZ ddlZeeeeee hZ!dej"# fZ$G dd dej%Z&ee e'eej(f Z)eee e'f ge
f Z*ee
gee e'f f Z+eee e
f ee
 f Z,eeeee f Z-ee,e-f Z.ed	e.d
Z/eddd
Z0ej1Z2e
e dddZ3ej4dddG dd de5Z6ej4ddddG dd de6e7Z8ej4dddG dd dZ9ej4dddG dd de9Z:ej4dddG dd de9Z;ed/dde)ed  ee* e:d!d"d#Z<eddddd$e)ed% ee+ ee ee ee e;d&d'd#Z<ed0dddddd(e)e ee* ee+ ee ee ee ee:e;f d)d*d#Z<d1dddddd(e)e ee* ee+ ee ee ee ee:e;f d)d+d#Z<e	j=e
 e d,d-d.Z>dS )2z
jsonlines implementation
    N)AnyCallableDictIterableIteratorListOptionalTupleTypeTypeVarUnioncastoverload)      )Literalc                   @   s$   e Zd Ze Ze Ze ZdS )DumpsResultConversionN)__name__
__module____qualname__enumauto	LeaveAsIsEncodeToBytesDecodeToString r   r   2lib/python3.8/site-packages/jsonlines/jsonlines.pyr   6   s   r   
TJSONValue)ZboundTRWReaderWriterBaseobjreturnc                 C   s   t dS )z;
    Fake dumps() function to use as a default marker.
    NNotImplementedError)r"   r   r   r   default_dumpsO   s    r&   T)auto_excauto_attribsc                   @   s   e Zd ZU dZeed< dS )Errorz
    Base error class.
    messageN)r   r   r   __doc__str__annotations__r   r   r   r   r)   V   s   
r)   F)r'   r(   initc                       sN   e Zd ZU dZeeef ed< eed< eeeef edd 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``.
    linelinenoN)r*   r0   r1   r#   c                    s,   |  | _|| _t | d| d d S )Nz (line ))rstripr0   r1   super__init__)selfr*   r0   r1   	__class__r   r   r5   u   s    
zInvalidLineError.__init__)r   r   r   r+   r   r,   bytesr-   intr5   __classcell__r   r   r7   r   r/   _   s   
r/   )r(   reprc                   @   s   e Zd ZU dZejdddZeej	e
 ej	e df ed< ejdddZeed< ejdddZeed< ddd	d
Ze
dddZe
dddZeedddZeee  ee eej ddddZdS )r    zJ
    Base class with shared behaviour for both the reader and writer.
    NFdefaultr.   _fp_closed_should_close_fpr#   c                 C   s.   | j r
dS d| _ | jdk	r*| jr*| j  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)r@   r?   rA   closer6   r   r   r   rC      s
    zReaderWriterBase.closec                 C   s0   t | j}|  }d| dt| dd| dS )Nz<jsonlines. at 0xxz
 wrapping >)typer   _repr_for_wrappedid)r6   Zcls_namewrappedr   r   r   __repr__   s    
zReaderWriterBase.__repr__c                 C   s   t d S Nr$   rD   r   r   r   rI      s    z"ReaderWriterBase._repr_for_wrapped)r6   r#   c                 C   s   | S rM   r   rD   r   r   r   	__enter__   s    zReaderWriterBase.__enter__)exc_typeexc_valexc_tbr#   c                 C   s   |    d S rM   )rC   )r6   rO   rP   rQ   r   r   r   __exit__   s    zReaderWriterBase.__exit__)r   r   r   r+   attribr?   r   typingIOr,   r9   r-   r@   boolrA   rC   rL   rI   r   rN   r   r
   BaseExceptiontypesTracebackTyperR   r   r   r   r   r    {   s    
 $
c                	   @   s  e Zd ZU dZeeje eje e	eeef  f e
d< ejddZeeeeeef f  e
d< ejeddZee
d< d	d
ddZedddded	 ed eedddZeddded	 ed eee dddZedddee ed eedddZeddee ed eee dddZeddddeee  eeee dddZd	dddeee  eeee dddZeddddded	 ed eeee dddZedddded	 ed eeee dddZedddd ee ed eeee dd!dZeddd"ee ed eeeee  dd#dZedddddeee  eeeeee  dd$dZd*eee  eeeeee  dd%dZee d
d&d'Zed
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.

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

    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.

    :param file_or_iterable: file-like object or iterable yielding lines as
        strings
    :param loads: custom json decoder callable
    _file_or_iterableF)r.   
_line_iterTr>   Zkw_only_loadsNrB   c                 C   sB   t | jtjr0tttjt tjt	 f | j| _
t| jd| _d S )N   )
isinstancer\   ioIOBaser   r   rU   rV   r,   r9   r?   	enumerater]   rD   r   r   r   __attrs_post_init__   s    zReader.__attrs_post_init__.rH   
allow_none
skip_empty)rH   rg   rh   r#   c                C   s   d S rM   r   r6   rH   rg   rh   r   r   r   read   s    zReader.read)rH   rh   c                C   s   d S rM   r   ri   r   r   r   rj      s    )rg   rh   c                C   s   d S rM   r   ri   r   r   r   rj      s    )rh   c                C   s   d S rM   r   ri   r   r   r   rj      s    c                C   s   d S rM   r   ri   r   r   r   rj      s    c          
   
   C   s  | j rtd|dk	r&|tkr&tdz.t| j\}}|rR| sRt| j\}}q6W n tk
rn   tdY nX t	|t
rz|d}W n: tk
r } ztd| ||}||W 5 d}~X Y nX |tr|dd }z| |}W n< tk
r$ } ztd| ||}||W 5 d}~X Y nX |dkrF|r:dS td|||dk	rt	||}	|tkrv|	ott	|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``, 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: r`   zline contains invalid json: zline contains null valuez"line does not match requested type)r@   RuntimeErrorVALID_TYPES
ValueErrornextr]   r3   StopIterationEOFErrorra   r9   decodeUnicodeDecodeErrorr/   
startswithSKIPPABLE_SINGLE_INITIAL_CHARSr_   r:   rW   )
r6   rH   rg   rh   r1   r0   Zorig_excexcvalueZvalidr   r   r   rj     s\    
  
  



  )rH   rg   rh   skip_invalid)rH   rg   rh   rx   r#   c                C   s   d S rM   r   r6   rH   rg   rh   rx   r   r   r   iterL  s    	zReader.iter)rH   rh   rx   c                C   s   d S rM   r   ry   r   r   r   rz   X  s    	)rg   rh   rx   c                C   s   d S rM   r   ry   r   r   r   rz   d  s    	)rh   rx   c                C   s   d S rM   r   ry   r   r   r   rz   p  s    	c                C   s   d S rM   r   ry   r   r   r   rz   |  s    	c                 c   sR   z8z| j |||dV  W q tk
r2   |s. Y qX qW n tk
rL   Y nX dS )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.
        rf   N)rj   r/   rq   ry   r   r   r   rz     s      c                 C   s   |   S )z0
        See :py:meth:`~Reader.iter()`.
        )rz   rD   r   r   r   __iter__  s    zReader.__iter__c                 C   s:   | j d k	rt| j S t| jj}d| dt| jddS )N<rE   rF   rG   )r?   repr_for_fprH   r\   r   rJ   )r6   
class_namer   r   r   rI     s    

zReader._repr_for_wrapped)NFFF)!r   r   r   r+   r   rU   rV   r,   r9   r   r-   rS   rT   r]   r   r	   r:   default_loadsr_   LoadsCallablere   r   r   rW   	JSONValuerj   r   r
   r   r   rz   r{   rI   r   r   r   r   r[      s  
 (






H


    

!r[   c                   @   s   e Zd ZU dZejddZeej	e
 ej	e f ed< ejdddZeed< ejddd	Zeed
< ejddd	Zeed< ejddd	Zeed< ejedd	Zeed< ejejddZeed< ddddZeddddZee ddddZe
dddZdS )Writera  
    Writer for the jsonlines format.

    Instances can be used as a context manager.

    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.

    :param fp: writable file-like object
    :param compact: whether to use a compact output format
    :param sort_keys: whether to sort object keys
    :param dumps: custom encoder callable
    :param flush: whether to flush the file-like object after writing each line
    N)r>   r?   Fr=   _fp_is_binaryTr^   _compact
_sort_keys_flush_dumps_dumps_result_conversionrB   c                 C   s   t | jtjrd| _nHt | jtjr,d| _n2z| jd W n tk
rV   d| _Y nX d| _| jt	krt
d| jd}| jr|jdd tjf |j| _| i }t |tr| jrtj| _nt |tr| jstj| _d S )NFT )Zensure_ascii	sort_keys),:)Z
separators)ra   r?   rb   
TextIOBaser   rc   write	TypeErrorr   r&   dictr   r   updatejsonZJSONEncoderencoder,   r   r   r   r9   r   )r6   Zencoder_kwargsZsample_dumps_resultr   r   r   re     s,    


zWriter.__attrs_post_init__r!   c                 C   sx   | j rtd| |}| jtjkr.| }n| jtjkrB| }| j	}|
| |
| jr`dnd | jrt|  dS )zg
        Encode and write a single object.

        :param obj: the object to encode and write
        zwriter is closed   

N)r@   rl   r   r   r   r   r   r   rr   r?   r   r   r   flush)r6   r"   r0   fpr   r   r   r     s    


zWriter.write)iterabler#   c                 C   s   |D ]}|  | qdS )ze
        Encode and write multiple objects.

        :param iterable: an iterable of objects
        N)r   )r6   r   r"   r   r   r   	write_all  s    zWriter.write_allc                 C   s
   t | jS rM   )r}   r?   rD   r   r   r   rI     s    zWriter._repr_for_wrapped)r   r   r   r+   rS   rT   r?   r   rU   rV   r,   r9   r-   r   rW   r   r   r   r&   r   DumpsCallabler   r   r   re   r   r   r   r   rI   r   r   r   r   r     s   
( !	r   .)loadsr)filemoder   r#   c                C   s   d S rM   r   )r   r   r   r   r   r   open#  s    r   )dumpscompactr   r   )wa)r   r   r   r   r   r   r#   c                C   s   d S rM   r   )r   r   r   r   r   r   r   r   r   r   -  s    
r   r   r   r   r   )r   r   r   r   r   r   r   r#   c                C   s   d S rM   r   )r   r   r   r   r   r   r   r   r   r   r   :  s    c                C   s~   |dkrt d|dkrtnt}|dkr,dnd}tj| |d |d}	t|||||d}
d	d
 |
 D }
||	f|
}d|_|S )u  
    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: name or ‘path-like object’ of the file to open
    :param mode: whether to open the file for reading (``r``),
        writing (``w``) or appending (``a``).
    >   r   r   r   z&'mode' must be either 'r', 'w', or 'a'r   z	utf-8-sigrk   t)r   encodingr   c                 S   s   i | ]\}}|d k	r||qS rM   r   ).0keyrw   r   r   r   
<dictcomp>w  s       zopen.<locals>.<dictcomp>T)rn   r[   r   builtinsr   r   itemsrA   )r   r   r   r   r   r   r   clsr   r   kwargsinstancer   r   r   r   H  s     ")r   r#   c                 C   s(   t | dd}|dk	rt|S t| S dS )z@
    Helper to make a useful repr() for a file-like object.
    nameN)getattrr<   )r   r   r   r   r   r}   }  s    r}   ).).)r   )?r+   r   codecsr   rb   r   ossysrY   rU   r   r   r   r   r   r   r   r	   r
   r   r   r   r   version_infor   Ztyping_extensionsrS   rW   r   floatr:   listr,   rm   BOM_UTF8rr   ru   Enumr   r9   PathLikeZOpenabler   r   ZJSONCollectionZ
JSONScalarr   r   r   r   r   r&   s	Exceptionr)   rn   r/   r    r[   r   r   rV   r}   r   r   r   r   <module>   s   <
-  m 	 
 
5