Skip to main content

Access Python Classes Safely

Project description

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

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:

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

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

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:

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

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

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.

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

safedot-1.0.0.tar.gz (18.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

safedot-1.0.0-py3-none-any.whl (14.8 kB view details)

Uploaded Python 3

File details

Details for the file safedot-1.0.0.tar.gz.

File metadata

  • Download URL: safedot-1.0.0.tar.gz
  • Upload date:
  • Size: 18.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for safedot-1.0.0.tar.gz
Algorithm Hash digest
SHA256 1d5c46fa5412218d1dd87062b4c26596531ba73bb3c018797ad0ba246409bdce
MD5 34bdbd2af90d8acf2aeb2943203c908b
BLAKE2b-256 bfbf8c6584cfcc5dcfbed038e484b85f8e6468cbfd076f468078e732f97771f0

See more details on using hashes here.

File details

Details for the file safedot-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: safedot-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 14.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for safedot-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6b4e72e43c98e3967cdbfbd8dc020f9289d24228b34b3cda298dd394ab3dfeb1
MD5 a778ba99a77f7abc3486afcf940853e7
BLAKE2b-256 ed5436bde687748a5a0c3d4d4f1e06be007e3e3d7eb1d22c34ec10efd9e1dd9f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page