Metadata-Version: 2.4
Name: SafeDot
Version: 1.0.0
Summary: Access Python Classes Safely
Author-email: Phillip Harry T <philliptinsley44@gmail.com>
License: Apache NON-AI License, Version 2.0
        
        TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
        1. Definitions.
        
        “License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
        
        “Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
        
        “Legal Entity” shall mean the union of the acting entity and all other entities that control, are controlled by,
        or are under common control with that entity. For the purposes of this definition, “control” means (i) the power, direct or indirect,
        to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%)
        or more of the outstanding shares, or (iii) beneficial ownership of such entity.
        
        “You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.
        
        “Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source,
        and configuration files.
        
        “Object” form shall mean any form resulting from mechanical transformation or translation of a Source form, including
        but not limited to compiled object code, generated documentation, and conversions to other media types.
        
        “Work” shall mean the work of authorship, whether in Source or Object form, made available under the License,
        as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
        
        “Derivative Works” shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and
        for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship.
        For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name)
        to the interfaces of, the Work and Derivative Works thereof.
        
        “Contribution” shall mean any work of authorship, including the original version of the Work and any modifications or additions to
        that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or
        by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, “submitted”
        means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to
        communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of,
        the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated
        in writing by the copyright owner as “Not a Contribution.”
        
        “Contributor” shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and
        subsequently incorporated within the Work.
        
        2. Grant of Copyright License.
        
        Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
        no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform,
        sublicense, and distribute the Work and such Derivative Works in Source or Object form,
        under the following conditions:
        
          2.1. You shall not use the Covered Software in the creation of an Artificial Intelligence training dataset,
          including but not limited to any use that contributes to the training or development of an AI model or algorithm,
          unless You obtain explicit written permission from the Contributor to do so.
        
          2.2. You acknowledge that the Covered Software is not intended for use in the creation of an Artificial Intelligence training dataset,
          and that the Contributor has no obligation to provide support or assistance for any use that violates this license.
        
        3. Grant of Patent License.
        
        Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
        royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import,
        and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are
        necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which
        such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit)
        alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement,
        then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
        
        4. Redistribution.
        
        You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications,
        and in Source or Object form, provided that You meet the following conditions:
        
          1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
        
          2. You must cause any modified files to carry prominent notices stating that You changed the files; and
        
          3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark,
          and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
          
          4. If the Work includes a “NOTICE” text file as part of its distribution, then any Derivative Works that You distribute
          must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that
          do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works;
          or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear.
          The contents of the NOTICE file are for informational purposes only and do not modify the License.
        
        You may add Your own attribution notices within Derivative Works that You distribute,
        alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as
        modifying the License.
        You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use,
        reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction,
        and distribution of the Work otherwise complies with the conditions stated in this License.
        
        5. Submission of Contributions.
        
        Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor
        shall be under the terms and conditions of this License, without any additional terms or conditions.
        Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed
        with Licensor regarding such Contributions.
        
        6. Trademarks.
        
        This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor,
        except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
        
        7. Disclaimer of Warranty.
        
        Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions)
        on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation,
        any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
        You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated
        with Your exercise of permissions under this License.
        
        8. Limitation of Liability.
        
        In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise,
        unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing,
        shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages
        of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages
        for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses),
        even if such Contributor has been advised of the possibility of such damages.
        
        9. Accepting Warranty or Additional Liability.
        
        While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support,
        warranty, indemnity, or other liability obligations and/or rights consistent with this License.
        However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility,
        not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by,
        or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
        
        END OF TERMS AND CONDITIONS
Keywords: class,get,set,safe,access,dotget,safedot,SafeDot,.get,.set,chainlink
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Intended Audience :: Information Technology
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# SafeDot: Set and Get Python Classes Safely


Python classes are flexible, but if you're using annotations on them, you probably want to make sure the values you're getting and setting match those annotations. SafeDot is here for those times.   
It also provides a safe way of chaining together accessors on your classes. (more on this later)
There are 3 key functions in SafeDot.

## Installing 

Install with 

```
pip install SafeDot
```  
and import with 
```  
from SafeDot import *
``` 

## dot_set

This static method can be imported with 
```
from SafeDot import dot_set
```

The purpose of this function is to enforce the annotations on your class while setting a value.   
The function has 3 mandatory parameters 
```
dot_set(instance, attribute, value)
```   
The instance is the instance you're setting the __attribute__ on.  
When setting it, the function first checks that the provided attribute is in the annotations of the instance's class.  
If it is, it then checks if the incoming __value__ is of the same type as the annotation. The type checking extends to unions of types and subtypes as well.  
Importantly it also checks Literal annotations, so if you annotate your attribue with 
Literal['val1', 'val2', 'val3'] but pass in 'val4', there'll be an error. 
### Errors 
As mentioned above there is a series of checks; if these don't pass there is an error. The reason I say error rather than exception, is the error's behaviour depends on the final, and optional, parameter of the function. *error_list*.   
By default any check that fails will throw an exception, so the attribue not being found on an instance will result in the exception "Attribue {x} not found in {type(y)} annotations".  
However, if you pass in error_list, these errors are no longer exceptions, and will quietly add to the provided error list.  
In the case of an error, no value is returned

## dot_get
imported with 
```
from SafeDot import dot_get
```   

The purpose of this function is to enforce annotations on your class while getting a value. It makes sure you're not looking in the wrong places and unknowingly retrieving default values.  
It also allows you to pass in specific errors when values are not found. This can be useful when you want to bubble up errors that are helpful to users, and you want them to be defined at the point of accessing the instance.  
The function has a lot of optional arguments, but there are only 2 mandatory ones.  
The most basic call to the function looks like 
```  
dot_get(instance, attribute)
```
When called this way, with no optional arguments, the function will check that the attribute is in the annotations of the instance's class, and that it is an attribute on the specific instance.  
If either of these is false, there is an error.  
Much like dot_set above, the behaviour of errors depends on the *error_list* being passed in.  
This is an optional argument.  
If you don't pass it in, the checks will throw exceptions.  
If you pass it in, an error will be silently added to the provided list.  
### Optional Arguments 
In addition to the error_list, there are the following optional arguments 
- generic_error
- unannotated_error
- missing_error
- is_none_error  
If you don't care about defining specific error messages, and you don't care about potentially None being returned, skip this.  
If you do care about being able to provide specific error messages depending on the error encountered, pass in these arguments.  
#### generic error
This takes precedence over the inbuilt error, but will be overriden by the following errors if provided.   
For example you may have a data structure that isn't named in a manner that's very useful for an end-user of your software. You wouldn't want an exception to bubble up to show them your internal class names; When calling dot_get on your InternalClass123 you pass in the generic_error 'Error in Calendar retrieval'. Now when the code sees attribute is not on the instance, instead of the error being 'Attribute "attribute" not found in annotations of "InternalClass123" class, the error will be 'Error in Calendar retrieval'. This is still in conjunction with the error_list, so it will throw an exception unless the error_list is passed in.  
#### unannotated error
This takes precedence over the generic_error and the inbuilt error in the specific case where the attribute is not found in the annotations of the instance's class. For example

```python
class Example:
    att: int

instance = Example()
dot_get(instance, 'val', unannotated_error='Instance missing annotation')
```  
This code would throw the exception 'Instance missing annotation', rather than the inbuilt message of 'Attribute "val" not found in "Example" annotations'  
#### missing error
This takes precendece over the generic_error and the inbuilt error in the specific case where the attribute is not found in the attributes of the specific instance passed in. For example:   

```python
class Example:
    att: int

instance = Example()
dot_get(instance, 'att', missing_error='Specific instance missing attribute')
```  
This code would throw the exception 'Specific instance missing attribute' rather than the inbuilt message of 'Attribute "att" not found on instance of "Example". It differs from the unannotated_error case because it's annotated, just not set.  
#### is_none error
This optional argument actually changes the behaviour, allowing the function to make an extra check, and providing an error message if supplied.  
When you supply this argument, assuming all other checks pass and the value in the attribute is found, if it's None, cause an error (again, if you provide error_list this will be silent, otherwise it's an exception being thrown).  
If you don't provide it, dot_get doesn't care that it found None, it returns the None.
Example  
```python
class Example:
    att: str
instance = Example()
instance.att = None
resp = dot_get(instance, 'att', is_none_error='att was none')
```
raises the exception 'att was none'. If you didn't pass this argument in resp would be set to None, with no exception. 

## chain_get and ChainLink 
It's also useful to be able to access nested classes and still make use of the dot_get.  
In fact the use-case of dot_get becomes even more apparent with nested classes, as you can become less sure of their contents the deeper you go.  
the function chain_get takes 2 mandatory arguments  
```
chain_get(instance, chain_list)
```  
instance is the class you're accessing, chain_list is a list of ChainLink instances.  
This is a class in the SafeDot library. It basically allows us to define dot_get behaviour that (as the name suggests) chains together.  
If you have a nested class, rather than writing a dot_get, followed by another dot_get, you can define two ChainLink instances and pass them into the chain_list.  
A ChainLink has 2 main arguments, only the attribute is mandatory of these
```python 
ChainLink(attribute, index)
```
attribute is used to access the instance, and if the found value is expected to be a list, the index is used to index into that list. 
The remaining arguments of the ChainLink are exactly like dot_get. They are 
- generic_error
- unannotated_error
- missing_error
- is_none_error    
  
And them being attributes of the ChainLink means you can define these errors specifically for each stage of accessing nested classes. For further information about these scroll up.  
For an example of their use, keep reading
### Example of chain_get: 
```python
class inner:
    innerval: str

class outer:
    att: inner

inner_instance = inner()
inner_instance.innerval = 'test'

outer_instance = outer()
outer_instance.att = inner_instance

resp = chain_get(outer_instance, [ChainLink('att'), ChainLink('innerval')])
```
This will return 'test' for resp. But the same validation applies here as in dot_get, so the classes missing annotations or the instance missing attributes will cause error.  

*if you just want a chain accessor for classes, use the ChainLinks, but also pass in error_list. If you have no intention of reading the list it's effectively just silencing the exceptions and validation. Example
```python
resp = chain_get(outer_instance, [ChainLink('att'), ChainLink('innerval')], error_list=[])
```

### Example of chain_get with index
If you have lists or tuples in the nesting, use the index attribute when creating a ChainLink  
```python
class inner:
    innerval: str

class outer:
    att: list[inner]

inner_instance = inner()
inner_instance.innerval = 'test'

outer_instance = outer()
outer_instance.att = [inner_instance]

resp = chain_get(outer_instance, [ChainLink('att', 0), ChainLink('innerval')])
```

### Example of chain_get with specific errors
If you want specific errors to match the section of the nesting you're accessing, they can be passed in with each ChainLink.  For example, if you care that the innerval attribue of the inner class is present, pass in 'missing_error' to the ChainLink.  
These validations still happen without the errors being passed in, it's the same as dot_get, this is just allowing a specific message to match an error.  
```python
class inner:
    innerval: str

class outer:
    att: list[inner]

inner_instance = inner()

outer_instance = outer()
outer_instance.att = [inner_instance]

resp = chain_get(outer_instance, [ChainLink('att', 0), ChainLink('innerval', missing_error='Innerval missing')])
```
would raise the exception 'Innerval missing', because the validation didn't find that attribute, and you passed that specific error message in.

chain_get does also take the *error_list* optional argument. Which will, like in dot_get and dot_set, silence the exceptions and instead add to that list. 


