o
    e9                     @   s  U 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mZ d dlmZ d dlmZ d dlm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$ d dl%m&Z& ej'dkr{d d	lm(Z( nd d	l)m(Z( ed
ddZ*e
ej+j, Z-ee.e-f Z/dZ0ee1d< dZ2ee1d< da3e4e1d< deddZ5deddZ6ej7de4ded fddZ8e	dfdddee.ef dee.ef d eee.ef  d!ed ddf
d"d#Z9e	dfdee.ef dee.ef d eee.ef  d!ed$ deej+j, f
d%d#Z9	dgddd&d#Z9	dgdee.ef dee.ef d eee.ef  de-fd'd(Z:de;de.fd)d*Z<de4fd+d,Z=dee.ef dee.ef fd-d.Z>	dgd ee.ef d/ee. fd0d1Z?d2ej+j,de.fd3d4Z@d5e-de/fd6d7ZAd5e-de-fd8d9ZBd:e/de/fd;d<ZCd=e.d>e	e. de4fd?d@ZDdAe/de/fdBdCZEd2ej+j,de4fdDdEZFd5e-de/fdFdGZGd5e-de-fdHdIZHd5e-de-fdJdKZId5e-de-fdLdMZJdNeKdeeKddf fdOdPZLdQedReee.ef  defdSdTZM	dgdee.ef d eee.ef  dee.ef fdUdVZNG dWdX dXej,ZOG dYdZ dZZPeP ZQee1d[< G d\d dZRd]d^ ZSG d_d` d`ZTG dadb dbZUdNe*de*fdcddZVdS )h    N)AnySequenceListDictOptionalDefaultDictTupleIterableType	GeneratorUnionoverloadLiteralTypeVar)zip_longest)version)Final)Version)vegalite)      )Self_TSchemaBase
SchemaBase)boundzurn:vega-lite-schema_VEGA_LITE_ROOT_URIz'http://json-schema.org/draft-07/schema#_DEFAULT_JSON_SCHEMA_DRAFT_URLT
DEBUG_MODEreturnc                   C      da d S )NTr    r!   r!   ED:\Projects\ConvertPro\env\Lib\site-packages\altair/utils/schemapi.pyenable_debug_modeK      r#   c                   C   r   )NFr    r!   r!   r!   r"   disable_debug_modeP   r$   r%   arg)NNNc                 c   s"    t }| a zd V  W |a d S |a w Nr    )r&   originalr!   r!   r"   
debug_modeU   s   r)   .)raise_errorspecschema
rootschemar*   c                C      d S r'   r!   r+   r,   r-   r*   r!   r!   r"   validate_jsonschema`      r0   Fc                C   r.   r'   r!   r/   r!   r!   r"   r0   k   r1   c                C   s\   t | ||d}|r,t|}t|}t|}t|}t| d d }||_|r*||S dS )a!  Validates the passed in spec against the schema in the context of the
    rootschema. If any errors are found, they are deduplicated and prioritized
    and only the most relevant errors are kept. Errors are then either raised
    or returned, depending on the value of `raise_error`.
    r-   r   N)_get_errors_from_spec_get_leaves_of_error_tree_group_errors_by_json_path#_subset_to_most_specific_json_paths_deduplicate_errorslistvalues_all_errors)r+   r,   r-   r*   errorsZleaf_errorsgrouped_errorsZ
main_errorr!   r!   r"   r0   v   s   c                 C   s   t |p|}tjd|i}i }t|dr|j|d< t r+t|}t|p%|||d< n|dur5tj	
|nd|d< ||fi |}t|| }|S )zUses the relevant jsonschema validator to validate the passed in spec
    against the schema using the rootschema to resolve references.
    The schema and rootschema themselves are not validated but instead considered
    as valid.
    $schemaFORMAT_CHECKERZformat_checkerregistryNresolver)_get_json_schema_draft_url
jsonschemaZ
validatorsZvalidator_forhasattrr>   _use_referencing_library_prepare_references_in_schema_get_referencing_registryRefResolverfrom_schemar8   Ziter_errors)r+   r,   r-   json_schema_draft_urlZvalidator_clsZvalidator_kwargs	validatorr;   r!   r!   r"   r3      s&   


r3   c                 C   s   |  dtS )Nr=   )getr   r,   r!   r!   r"   rA      s   rA   c                  C   s   t d} t| tdkS )ziIn version 4.18.0, the jsonschema package deprecated RefResolver in
    favor of the referencing library.rB   z4.18)importlib_versionr   )Zjsonschema_version_strr!   r!   r"   rD      s   rD   c                    s<   t | } dtttf dtttf f fdd  | } | S )Ndr   c                    s   |   D ];\}}|dkrt| |  | |< qt|tr! || |< qt|tr?g }|D ]}t|tr5 |}|| q*|| |< q| S )z}Add _VEGA_LITE_ROOT_URI in front of all $ref values. This function
        recursively iterates through the whole dictionary.$ref)itemsr   
isinstancedictr8   append)rN   keyvalueZprepared_valuesv_prepare_refsr!   r"   rX      s   


z4_prepare_references_in_schema.<locals>._prepare_refs)copydeepcopyr   strr   rL   r!   rW   r"   rE      s   
&rE   rI   c                 C   sH   dd l }dd l}|d u rt| }|j|}|| }| jt|dS )Nr   )uriresource)	referencingZreferencing.jsonschemarA   rB   Zspecification_withZcreate_resourceZRegistryZwith_resourcer   )r-   rI   r^   specificationr]   r!   r!   r"   rF      s   

rF   errc                 C   s@   d}| j D ]}t|tr|dt| d 7 }q|d| 7 }q|S )zDrop in replacement for the .json_path property of the jsonschema
    ValidationError class, which is not available as property for
    ValidationError with jsonschema<4.0.1.
    More info, see https://github.com/altair-viz/altair/issues/3038
    $[].)absolute_pathrQ   intr[   )r`   pathelemr!   r!   r"   
_json_path  s   

ri   r;   c                 C   s:   t t}| D ]}t|dt|}|| | qt|S )a  Groups errors by the `json_path` attribute of the jsonschema ValidationError
    class. This attribute contains the path to the offending element within
    a chart specification and can therefore be considered as an identifier of an
    'issue' in the chart that needs to be fixed.
    	json_path)collectionsdefaultdictr8   getattrri   rS   rR   )r;   errors_by_json_pathr`   Zerr_keyr!   r!   r"   r5     s
   
r5   c                 C   s4   g }| D ]}|j r|t|j  q|| q|S )a.  For each error in `errors`, it traverses down the "error tree" that is generated
    by the jsonschema library to find and return all "leaf" errors. These are errors
    which have no further errors that caused it and so they are the most specific errors
    with the most specific error messages.
    )contextextendr4   rS   )r;   leavesr`   r!   r!   r"   r4   +  s   r4   rn   c                 C   s4   i }|   D ]\}}t|t|  s|||< q|S )a  Removes key (json path), value (errors) pairs where the json path is fully
    contained in another json path. For example if `errors_by_json_path` has two
    keys, `$.encoding.X` and `$.encoding.X.tooltip`, then the first one will be removed
    and only the second one is returned. This is done under the assumption that
    more specific json paths give more helpful error messages to the user.
    )rP   *_contained_at_start_of_one_of_other_valuesr8   keys)rn   Zerrors_by_json_path_specificrj   r;   r!   r!   r"   r6   ?  s   	r6   xr9   c                    s   t  fdd|D S )Nc                 3   s"    | ]} |kr|  V  qd S r'   )
startswith).0rU   rt   r!   r"   	<genexpr>T  s     z=_contained_at_start_of_one_of_other_values.<locals>.<genexpr>)any)rt   r9   r!   rw   r"   rr   Q  s   rr   r<   c           
      C   s   i }|   D ]8\}}t|}ttd}g }|  D ]\}}||d}	|	dur+|	|}|t| qdd |D }|||< q|S )zSome errors have very similar error messages or are just in general not helpful
    for a user. This function removes as many of these cases as possible and
    can be extended over time to handle new cases that come up.
    )enumadditionalPropertiesNc                 S   s   g | ]}t |s|qS r!   )_is_required_value_errorrv   r`   r!   r!   r"   
<listcomp>t  s
    z'_deduplicate_errors.<locals>.<listcomp>)rP   _group_errors_by_validator_deduplicate_enum_errors)_deduplicate_additional_properties_errorsrK   rp   _deduplicate_by_message)
r<   Zgrouped_errors_deduplicatedrj   Zelement_errorserrors_by_validatorZdeduplication_functionsZdeduplicated_errorsrJ   r;   Zdeduplication_funcr!   r!   r"   r7   W  s"   	
r7   c                 C   s   | j dko
| jdgkS )NrequiredrU   )rJ   validator_value)r`   r!   r!   r"   r|   |  s   r|   c                 C   s,   t t}| D ]
}||j | qt|S )ao  Groups the errors by the json schema "validator" that casued the error. For
    example if the error is that a value is not one of an enumeration in the json schema
    then the "validator" is `"enum"`, if the error is due to an unknown property that
    was set although no additional properties are allowed then "validator" is
    `"additionalProperties`, etc.
    )rk   rl   r8   rJ   rS   rR   )r;   r   r`   r!   r!   r"   r     s
   	r   c                 C   sN   t | dkr%dd | D }g }t|| D ]\}}t||s"|| q|} | S )an  Deduplicate enum errors by removing the errors where the allowed values
    are a subset of another error. For example, if `enum` contains two errors
    and one has `validator_value` (i.e. accepted values) ["A", "B"] and the
    other one ["A", "B", "C"] then the first one is removed and the final
    `enum` list only contains the error with ["A", "B", "C"].
       c                 S   s   g | ]}d  |jqS ),)joinr   r}   r!   r!   r"   r~         z,_deduplicate_enum_errors.<locals>.<listcomp>)lenziprr   rS   )r;   Zvalue_stringsZlongest_enumsZ	value_strr`   r!   r!   r"   r     s   

r   c                    s\   t | dkr,| d j  dur, jdkr,t fdd| dd D r,t| dd d	g} | S )
a  If there are multiple additional property errors it usually means that
    the offending element was validated against multiple schemas and
    its parent is a common anyOf validator.
    The error messages produced from these cases are usually
    very similar and we just take the shortest one. For example,
    the following 3 errors are raised for the `unknown` channel option in
    `alt.X("variety", unknown=2)`:
    - "Additional properties are not allowed ('unknown' was unexpected)"
    - "Additional properties are not allowed ('field', 'unknown' were unexpected)"
    - "Additional properties are not allowed ('field', 'type', 'unknown' were unexpected)"
    r   r   NanyOfc                 3   s    | ]}|j  u V  qd S r'   parentr}   r   r!   r"   rx     s    z<_deduplicate_additional_properties_errors.<locals>.<genexpr>c                 S   s
   t | jS r'   )r   messagerw   r!   r!   r"   <lambda>  s   
 z;_deduplicate_additional_properties_errors.<locals>.<lambda>)rT   )r   r   rJ   allminr;   r!   r   r"   r     s   

r   c                 C   s   t dd | D  S )zjDeduplicate errors by message. This keeps the original order in case
    it was chosen intentionally.
    c                 S   s   i | ]}|j |qS r!   r   rv   er!   r!   r"   
<dictcomp>      z+_deduplicate_by_message.<locals>.<dictcomp>)r8   r9   r   r!   r!   r"   r     s   r   clsc                 c   sN    t  }| h}|r%||O }t jdd |D  }|| D ]} | V  q|s	dS dS )z=Breadth-first sequence of all classes which inherit from cls.c                 s   s    | ]	}t | V  qd S r'   )set__subclasses__)rv   r   r!   r!   r"   rx     s    z_subclasses.<locals>.<genexpr>N)r   union)r   seenZcurrent_setr!   r!   r"   _subclasses  s   r   objro   c                    s   t | tr| jd dS t | tttjfr fdd| D S t | tr. fdd|  D S t	| dr7|  S t | tj
rAt| S t | tjtjfrQt|  S | S )z+Convert an object to a dict representation.F)validatero   c                    s   g | ]}t | qS r!   )_todictrv   rV   ro   r!   r"   r~         z_todict.<locals>.<listcomp>c                    s$   i | ]\}}|t ur|t| qS r!   )	Undefinedr   rv   krV   r   r!   r"   r        $ z_todict.<locals>.<dictcomp>to_dict)rQ   r   r   r8   tuplenpZndarrayrR   rP   rC   numberfloatpd	TimestampZ
datetime64	isoformat)r   ro   r!   r   r"   r     s   


r   c                 C   s   t  r!t|p| }| }d| v r|t| d  j} d| v s| S tj|p'| }d| v rJ|	| d 
}|} W d   n1 sAw   Y  d| v s-| S )zeResolve schema references until there is no $ref anymore
    in the top-level of the dictionary.
    rO   N)
rD   rF   r@   lookupr   contentsrB   rG   rH   Z	resolving)r,   r-   r?   Zreferencing_resolverr@   resolvedr!   r!   r"   _resolve_references  s$   
	r   c                       s   e Zd ZdZdddejddf fddZdefd	d
ZdefddZ	de
defddZdejjdefddZdejjded fddZedee defddZde
defddZ  ZS )SchemaValidationErrorzBA wrapper for jsonschema.ValidationError with friendlier tracebackr   r   r`   r   Nc                    sR   t  jdi |  || _t|dt|dt||gi| _| j| _| 	 | _d S )Nr:   rj   r!   )
super__init__Z	_contentsr   rm   ri   _errorsr   Z_original_message_get_message)selfr   r`   	__class__r!   r"   r     s   zSchemaValidationError.__init__c                 C   s   | j S r'   r   r   r!   r!   r"   __str__  s   zSchemaValidationError.__str__c                    s   ddt dtdt fdd g }t| j d d D ]
}|| | qd}t|d	kr= fd
dt|d	dD }|d7 }|d	|7 }|S )N   r   indentr   c                 S   sP   g }t | dD ]\}}|dkrt|dkrd| | }|| q	d|S )N
r    )	enumeratesplitr   rS   r   )r   r   Zmodified_linesidxliner!   r!   r"   indent_second_line_onwards  s   
zFSchemaValidationError._get_message.<locals>.indent_second_line_onwardsr    r   c                    s$   g | ]\}} d | d| qS )zError z: r!   )rv   Zerror_idmr   r!   r"   r~   !  s    z6SchemaValidationError._get_message.<locals>.<listcomp>)startzMultiple errors were found.



)r   )
r[   rf   r8   r   r9   rS   _get_message_for_errors_groupr   r   r   )r   Zerror_messagesr;   r   r!   r   r"   r     s   

z"SchemaValidationError._get_messager;   c                 C   s8   |d j dkr| |d }| S | j|d}| S )Nr   r{   r   )rJ   (_get_additional_properties_error_message_get_default_error_messagestrip)r   r;   r   r!   r!   r"   r   )  s
   z3SchemaValidationError._get_message_for_errors_grouperrorc              	   C   sd   |  |}t|j }| |}|jdd dd }d|j d| d| d|j d		}|S )
zFOutput all existing parameters when an unknown parameter is specified.z(''r   `z` has no parameter named 'z!'

Existing parameter names are:
z
See the help for `z2` to read the full description of these parameters)	_get_altair_class_for_errorinspect	signature
parametersrs   _format_params_as_tabler   r   __name__)r   r   Z
altair_clsparam_dict_keysparam_names_tableZparameter_namer   r!   r!   r"   r   9  s   

z>SchemaValidationError._get_additional_properties_error_messagec                 C   sX   t |jD ] }t|tr%|d  |dd  }tt|d}|dur% |S q| jj}|S )zTry to get the lowest class possible in the chart hierarchy so
        it can be displayed in the error message. This should lead to more informative
        error messages pointing the user closer to the source of the issue.
        r   r   N)	reversedre   rQ   r[   upperrm   r   r   r   )r   r   Z	prop_nameZpotential_class_namer   r!   r!   r"   r   N  s   
z1SchemaValidationError._get_altair_class_for_errorr   c                 C   s<  t dd | D  \}}t|}d}t|}tt|d }t|| |}dtdtdtt fdd	}|||}	g }
g }d
}|	D ]}|
||||   |tdd |
d D  || }q?g }t	|
ddiD ]}|| qhd}|D ]'}t
|D ] \}}|| }d}|d||| 7 }|t|d kr|d7 }qzqt|S )z?Format param names into a table so that they are easier to readc                 S   s    g | ]}|d vr|t |fqS ))kwdsr   r   )rv   namer!   r!   r"   r~   i  s
    
zASchemaValidationError._format_params_as_table.<locals>.<listcomp>P   g      ?npr   c                 S   s,   | | d g| |  | | g|| |    S )Nr   r!   )r   r   r!   r!   r"   split_into_equal_partsy  s   ,zMSchemaValidationError._format_params_as_table.<locals>.split_into_equal_partsr   c                 S   s   g | ]}t |qS r!   r   )rv   
param_namer!   r!   r"   r~     r   r   	fillvaluer   r   z{:<{}}r   r   )r   maxr   rf   r   ceilr   r   rS   r   r   format)r   Zparam_namesZname_lengthsZmax_name_lengthZmax_column_widthZnum_param_namesZsquare_columnscolumnsr   Zcolumn_heightsZparam_names_columnsZcolumn_max_widthsZlast_end_idxchZparam_names_rowsZlir   Zparam_names_rownumr   Zmax_name_length_columnZ
column_padr!   r!   r"   r   c  sJ   	


z-SchemaValidationError._format_params_as_tablec           	      C   s  g }t |}d|v r|d D ]}|d|j  qd|v radd |d D }d}t|dkr6||d 7 }n&t|d	krJ||d  d
|d  7 }n|d|d d d|d   7 }|| |d }d|j d}|jrz|d|jd  d7 }t|dkr|d7 }n,t|dkr|d|d  d7 }ndd |D }|d7 }|ddd |D 7 }|d7 }| D ]\}}|dvr|ddd |D 7 }q|S )Nrz   zone of typec                 S   s   g | ]	}d |j  d qS )r   )r   r}   r!   r!   r"   r~     s    zDSchemaValidationError._get_default_error_message.<locals>.<listcomp>zof type r   r      z or z, r   z, or r   z' is an invalid valuez for `r   z.

z. Valid values are c                 S   s$   g | ]}|d    |dd  qS )r   r   N)r   rv   pointr!   r!   r"   r~     r   z. Valid values are:

r   c                 S   s   g | ]}d | qS )z- r!   r   r!   r!   r"   r~     r   r   )rz   r   c                 S   s   g | ]}|j qS r!   r   r   r!   r!   r"   r~     s    )r   rS   r   r   r   instancere   rP   )	r   r;   Zbullet_pointsr   r   typesr   r   rJ   r!   r!   r"   r     s>   $

z0SchemaValidationError._get_default_error_message)r   
__module____qualname____doc__rB   ValidationErrorr   r[   r   r   ValidationErrorListr   
exceptionsr   r
   r   staticmethodr	   r   r   __classcell__r!   r!   r   r"   r      s6    



8r   c                   @   s$   e Zd ZdZdZdd Zdd ZdS )UndefinedTypez3A singleton object for marking undefined parametersNc                 O   s,   t | j| stj| g|R i || _| jS r'   )rQ   _UndefinedType__instanceobject__new__)r   argskwargsr!   r!   r"   r     s   zUndefinedType.__new__c                 C   s   dS )Nr   r!   r   r!   r!   r"   __repr__  s   zUndefinedType.__repr__)r   r   r   r   r   r   r  r!   r!   r!   r"   r     s
    r   r   c                       sF  e Zd ZU dZdZeeeef  e	d< dZ
eeeef  e	d< dZee	d< deded	dfd
dZ	d>deeef dee d	efddZefddZ fddZdd Zdd Zdd Zdd Zdd Z	d?ddddedeee  d eeeef  d	efd!d"Z		#	d@dddded$ed%edeee  d eeeef  d	efd&d'Ze d	e!e"d  ddf fd(d)Z#e 		d>d*eded+eee"d    d	d fd,d-Z$e 	d?d.eded/ed	efd0d1Z%e 	dAd2eeef d3eeeef  d	dfd4d5Z&e dAd3ee d	efd6d7Z'e 	dAd8ed9ed3ee d	dfd:d;Z(d	ef fd<d=Z)  Z*S )Br   zBase class for schema wrappers.

    Each derived class should set the _schema class attribute (and optionally
    the _rootschema class attribute) which is used for validation.
    N_schema_rootschemaT _class_is_valid_at_instantiationr   r   r   c                 O   s~   | j d u rtd| j|rt|dksJ nt|dv s J t| d| t| d| tr;| jr=| j	dd d S d S d S )NzMCannot instantiate object of type {}: _schema class attribute is not defined.r   )r   r   _args_kwdsTr   )
r  
ValueErrorr   r   r   r   __setattr__r   r  r   )r   r   r   r!   r!   r"   r     s   

zSchemaBase.__init__deepignorec                    s   dd }d
dt t f fdd zt|}W n ty!   d}Y nw d}|r.|s. | |d	S td | j| ji | j}W d   n1 sGw   Y  |rct|tsUJ |D ]}|||||< qW|S )a  Return a copy of the object

        Parameters
        ----------
        deep : boolean or list, optional
            If True (default) then return a deep copy of all dict, list, and
            SchemaBase objects within the object structure.
            If False, then only copy the top object.
            If a list or iterable, then only copy the listed attributes.
        ignore : list, optional
            A list of keys for which the contents should not be copied, but
            only stored by reference.
        c                 S   sB   t | tr| jddS t | tr| d d  S t | tr|  S | S )NF)r  )rQ   r   rY   r8   rR   )r   r!   r!   r"   _shallow_copy  s   


z&SchemaBase.copy.<locals>._shallow_copyNr  c                    s    d u rg  t | trBtfdd| jD } fdd| j D }td | j|i |W  d    S 1 s;w   Y  d S t | trQ fdd| D S t | t	rb fdd|  D S | S )	Nc                 3   s    | ]} |V  qd S r'   r!   )rv   r&   
_deep_copyr!   r"   rx   )  s    z6SchemaBase.copy.<locals>._deep_copy.<locals>.<genexpr>c                    *   i | ]\}}||vr |d n|qS r  r!   r   r  r  r!   r"   r   *      z7SchemaBase.copy.<locals>._deep_copy.<locals>.<dictcomp>Fc                    s   g | ]} |d qS r  r!   r   r  r!   r"   r~   1  r   z7SchemaBase.copy.<locals>._deep_copy.<locals>.<listcomp>c                    r  r  r!   r   r  r!   r"   r   3  r  )
rQ   r   r   r  r  rP   r)   r   r8   rR   )r   r  r   r   r  r  r"   r  %  s"   

$

z#SchemaBase.copy.<locals>._deep_copyFTr  r'   )	r   r8   	TypeErrorr)   r   r  r  rQ   _get)r   r  r  r  Zdeep_is_listrY   attrr!   r  r"   rY   
  s$   

zSchemaBase.copyc                 C   s   | j |t}|tu r|}|S )z3Get an attribute, returning default if not present.)r  rK   r   )r   r  defaultr!   r!   r"   r  M  s   zSchemaBase._getc                    s^   |dkrt  || jv r| j| S ztt| j}W ||S  t y.   tt| j}Y ||S w )Nr  )AttributeErrorr  r   r   __getattr____getattribute__)r   r  Z_getattrr   r!   r"   r  T  s   

zSchemaBase.__getattr__c                 C      || j |< d S r'   r  r   itemvalr!   r!   r"   r
  a     zSchemaBase.__setattr__c                 C   s
   | j | S r'   r  )r   r  r!   r!   r"   __getitem__d  s   
zSchemaBase.__getitem__c                 C   r  r'   r  r  r!   r!   r"   __setitem__g  r!  zSchemaBase.__setitem__c                 C   sZ   | j r"dd t| j  D }dd| }d| jj|ddS d| jj| jd S )	Nc                 s   s(    | ]\}}|t urd ||V  qdS )z{}: {!r}N)r   r   rv   rT   r   r!   r!   r"   rx   l  s    
z&SchemaBase.__repr__.<locals>.<genexpr>r   z,
z{0}({{{1}
}})z
  z{}({!r})r   )	r  sortedrP   r   r   r   r   replacer  )r   r   r!   r!   r"   r  j  s   zSchemaBase.__repr__c                 C   s(   t | t |u o| j|jko| j|jkS r'   )r   r  r  )r   otherr!   r!   r"   __eq__x  s
   

zSchemaBase.__eq__)r  ro   r   ro   c             
      s4  |du ri } du rg  | j r| jst| j d |d}n^| j sr| j |di }d|v r?dvs:d dtfvr?|d fdd	| D   fd
d	 D dv rktd t	rkdd id< t|d}nt
d| j|rz| | W |S  tjy } zt| |dd}~ww |S )a  Return a dictionary representation of the object

        Parameters
        ----------
        validate : bool, optional
            If True (default), then validate the output dictionary
            against the schema.
        ignore : list[str], optional
            A list of keys to ignore. It is usually not needed
            to specify this argument as a user.
        context : dict[str, Any], optional
            A context dictionary. It is usually not needed
            to specify this argument as a user.

        Notes
        -----
        Technical: The ignore parameter will *not* be passed to child to_dict
        function calls.

        Returns
        -------
        dict
            The dictionary representation of this object

        Raises
        ------
        SchemaValidationError :
            if validate=True and the dict does not conform to the schema
        Nr   r   parsed_shorthandsortr   Zordinalc                    s&   i | ]\}}  |ttu r||qS r!   )rK   r   r   )r   r!   r"   r     s
    z&SchemaBase.to_dict.<locals>.<dictcomp>c                    s(   i | ]\}}|t  d g vr||qS )Z	shorthand)r8   r   r  r!   r"   r     s    "markzF{} instance has both a value and properties : cannot serialize to dict)r  r  r   rY   popr   updaterP   rQ   r[   r	  r   r   r   rB   r   r   )r   r   r  ro   resultr)  r`   r!   )r  r   r"   r     sN   $



zSchemaBase.to_dictr   r   	sort_keysc                K   s@   |du rg }|du ri }| j |||d}tj|f||d|S )a  Emit the JSON representation for this object as a string.

        Parameters
        ----------
        validate : bool, optional
            If True (default), then validate the output dictionary
            against the schema.
        indent : int, optional
            The number of spaces of indentation to use. The default is 2.
        sort_keys : bool, optional
            If True (default), sort keys in the output.
        ignore : list[str], optional
            A list of keys to ignore. It is usually not needed
            to specify this argument as a user.
        context : dict[str, Any], optional
            A context dictionary. It is usually not needed
            to specify this argument as a user.
        **kwargs
            Additional keyword arguments are passed to ``json.dumps()``

        Notes
        -----
        Technical: The ignore parameter will *not* be passed to child to_dict
        function calls.

        Returns
        -------
        str
            The JSON specification of the chart object.
        N)r   r  ro   )r   r/  )r   jsondumps)r   r   r   r/  r  ro   r  dctr!   r!   r"   to_json  s   (zSchemaBase.to_jsonc                 C   s   t tS )z5Return the set of classes used within cls.from_dict())r   r   r   r!   r!   r"   _default_wrapper_classes	  s   z#SchemaBase._default_wrapper_classesr2  _wrapper_classesc                 C   s2   |r|  | |du r|  }t|}||| S )a  Construct class from a dictionary representation

        Parameters
        ----------
        dct : dictionary
            The dict from which to construct the class
        validate : boolean
            If True (default), then validate the input against the schema.
        _wrapper_classes : iterable (optional)
            The set of SchemaBase classes to use when constructing wrappers
            of the dict inputs. If not specified, the result of
            cls._default_wrapper_classes will be used.

        Returns
        -------
        obj : Schema object
            The wrapped schema

        Raises
        ------
        jsonschema.ValidationError :
            if validate=True and dct does not conform to the schema
        N)r   r5  	_FromDict	from_dict)r   r2  r   r6  	converterr!   r!   r"   r8    s    
zSchemaBase.from_dictjson_stringr  c                 K   s    t j|fi |}| j||dS )a  Instantiate the object from a valid JSON string

        Parameters
        ----------
        json_string : string
            The string containing a valid JSON chart specification.
        validate : boolean
            If True (default), then validate the input against the schema.
        **kwargs :
            Additional keyword arguments are passed to json.loads

        Returns
        -------
        chart : Chart object
            The altair Chart object built from the specification.
        r  )r0  loadsr8  )r   r:  r   r  r2  r!   r!   r"   	from_json5  s   zSchemaBase.from_jsonr   r,   c                 C   s0   |du r| j }|dusJ t||| jp| j dS )zj
        Validate the instance against the class schema in the context of the
        rootschema.
        Nr2   )r  r0   r  )r   r   r,   r!   r!   r"   r   Q  s   zSchemaBase.validatec                 C   s.   |p| j }|dusJ t|| jp| j p|dS )zIResolve references in the context of this object's schema or root schema.Nr,   r-   )r  r   r  )r   r,   Zschema_to_passr!   r!   r"   resolve_referencesa  s   
zSchemaBase.resolve_referencesr   rU   c                 C   sB   t |i d}| |p| jdi }t|||i | jp| jdS )zf
        Validate a property against property schema in the context of the
        rootschema
        r   
propertiesr2   )r   r>  r  rK   r0   r  )r   r   rU   r,   propsr!   r!   r"   validate_propertyl  s
   zSchemaBase.validate_propertyc                    s    t tt  t| j  S r'   )r%  r8   r   __dir__r  rs   r   r   r!   r"   rB  z  s    zSchemaBase.__dir__)TNT)Tr   Tr'   )+r   r   r   r   r  r   r   r[   r   __annotations__r  r  boolr   r   r	   r8   r   rY   r   r  r  r
  r"  r#  r  r(  r   rR   r   rf   r3  classmethodr   r
   r5  r8  r<  r   r>  rA  rB  r   r!   r!   r   r"   r     s   
 

C	

]
	
/&

c                  O   s   | r| d S |S Nr   r!   )r   r   r!   r!   r"   _passthrough~  s   rH  c                   @   s   e Zd ZdZdZdeee  ddfddZe	dd	e
d
edefddZdddefde
deee  d	ee
 dee
 def
ddZdS )r7  a!  Class used to construct SchemaBase class hierarchies from a dict

    The primary purpose of using this class is to be able to build a hash table
    that maps schemas to their wrapper classes. The candidate classes are
    specified in the ``class_list`` argument to the constructor.
    )Zdefinitionstitledescriptionr=   id
class_listr   Nc                 C   s<   t t| _|D ]}|jd ur| j| |j | qd S r'   )rk   rl   r8   
class_dictr  hash_schemarS   )r   rL  r   r!   r!   r"   r     s   
z_FromDict.__init__Tr,   use_jsonc                    sX   j rt|trfdd| D }|r tj|dd}t|S  fdd t |S )a  
        Compute a python hash for a nested dictionary which
        properly handles dicts, lists, sets, and tuples.

        At the top level, the function excludes from the hashed schema all keys
        listed in `exclude_keys`.

        This implements two methods: one based on conversion to JSON, and one based
        on recursive conversions of unhashable to hashable types; the former seems
        to be slightly faster in several benchmarks.
        c                    s    i | ]\}}| j vr||qS r!   )_hash_exclude_keysr$  r4  r!   r"   r     s
    
z)_FromDict.hash_schema.<locals>.<dictcomp>T)r/  c                    sb   t | trt fdd|  D S t | trtt | S t | ts(t | tr/tt | S | S )Nc                 3   s     | ]\}}| |fV  qd S r'   r!   r   _freezer!   r"   rx     s    z9_FromDict.hash_schema.<locals>._freeze.<locals>.<genexpr>)rQ   rR   	frozensetrP   r   mapr8   r   )r   rQ  r!   r"   rR    s   

z&_FromDict.hash_schema.<locals>._freeze)rP  rQ   rR   rP   r0  r1  hash)r   r,   rO  sr!   )rR  r   r"   rN    s   

z_FromDict.hash_schemar2  r   r-   c              	      s  |du |du krt d|du r-|j}|dusJ rn|dur+|jdur+|jndp0|t|tr8|S |du rMj| }|rK|d }n|}t|}d|v sZd|v r|dg |dg  }|D ] }z	t	||d W n
 t
jy}   Y qhw j|||d  S t|tr|di }	i }
| D ]\}}||	v rj||	| d	}||
|< q|di |
S t|tr|d
i   fdd|D }||S ||S )z.Construct an object from a dict representationNz0Must provide either cls or schema, but not both.r   r   oneOfr2   )r,   r-   default_classr?  r=  rP   c                    s   g | ]
}j | d qS )r=  )r8  )rv   r   Zitem_schemar-   r   r!   r"   r~     s    z'_FromDict.from_dict.<locals>.<listcomp>r!   )r	  r  r  rQ   r   rM  rN  r   rK   r0   rB   r   r8  rR   rP   r8   )r   r2  r   r,   r-   rX  matchesZschemasZpossible_schemar@  r   rT   r   r!   rY  r"   r8    s`   






z_FromDict.from_dictrC  )r   r   r   r   rP  r	   r
   r   r   rF  rR   rE  rf   rN  rH  r   r   r8  r!   r!   r!   r"   r7    s*    &
	r7  c                   @   s2   e Zd ZdededdfddZdd Zd	d
 ZdS )_PropertySetterpropr,   r   Nc                 C   s   || _ || _d S r'   )r\  r,   )r   r\  r,   r!   r!   r"   r     s   
z_PropertySetter.__init__c                 C   s   || _ || _| jd dd| _| j d  | j dd   }tt|rpt	t|}|j
d}|dkrQ|jd | dd	| j td
|j|d    | _n|jdd	d | j | _t|| _t|| _|j| _| S 	 | S )NrJ  __z**r   r   zParameters
r   z    r   z

    r   )r   r   r,   r&  r   r\  r   rC   r   rm   findtextwrapdedentr   r   __signature__getfullargspec__wrapped__r   )r   r   r   Zproperty_nameZaltair_propZparameter_indexr!   r!   r"   __get__	  s0    


z_PropertySetter.__get__c                 O   s$   | j  }|r|d n||| j< |S rG  )r   rY   r\  )r   r   r  r   r!   r!   r"   __call__-  s   
z_PropertySetter.__call__)r   r   r   r[   rR   r   rd  re  r!   r!   r!   r"   r[    s    $r[  c                 C   s8   |   }|di  D ]\}}t| |t|| q| S )z>
    Decorator to add property setters to a Schema class.
    r?  )r>  rK   rP   setattrr[  )r   r,   r\  Z
propschemar!   r!   r"   with_property_setters4  s   rg  )r   N).r'   )Wrk   
contextlibrY   r   r0  sysr_  typingr   r   r   r   r   r   r   r	   r
   r   r   r   r   r   	itertoolsr   importlib.metadatar   rM   r   rB   Zjsonschema.exceptionsZjsonschema.validatorsnumpyr   Zpandasr   Zpackaging.versionr   Zaltairr   version_infor   Ztyping_extensionsr   r   r   r   r[   ZGroupedValidationErrorsr   rD  r   r   rE  r#   r%   contextmanagerr)   r0   r3   rR   rA   rD   rE   rF   ri   r5   r4   r6   rr   r7   r|   r   r   r   r   r   r   r   r   r   r   r   r   rH  r7  r[  rg  r!   r!   r!   r"   <module>   s  
@
	








'


/"#





%
"


 S    0