воскресенье, 19 января 2020 г.

Safety in resource management in Python

Untitled

Yet another example of the type safety in Python maybe a resources management. We can use typing to ensure that resources were released, so no any resoucres leak. Yes, it's possible. The idea is that we will check in compile time with types that resoucres were released by checking that they were returned as appropriated type after its usage. Look the example:

If we will try to ommit return statement in the use_resources() function, then we will get an error Missing return statement from mypy. OK, if we will try to return None, then the error will be Incompatible return value type (got "None", expected "Resources[Free]"). OK, we will return the resource itself: return r. But an error again, now: Incompatible return value type (got "Resources[Hold]", expected "Resources[Free]").

It's a very good error: it says us that we don't release resources, we complete in the Resources[Hold] state. To fix it we will return release_resources(r) and now all is fine. The function use_resources() is wrapper which wraps the usage of them, tracks correct state of their life-cycle. It's typical for Haskell with phantom types, we tried to create one here, in Python. So, the function gets acquired resources, uses them and then releases them, and we will not forget to call release_resources().

PS. Those 3 resource related function can be implemented as class methods of Resources class.

суббота, 18 января 2020 г.

Yet another example of type safety in Python

Untitled

Python can be safe (if we need it) too. Another example is: let's say we want to implement a function unique(). It may looks like:

Truth is that data should be sorted - we don't want to sort it because data items maybe are sorted already. So, instead to write docstring about this our requirement ("data should be sorted") we can specify this requirement as a type, so it will prevent a client from passing of data which was not sorted, so the check will work at compile time:

And if we try to pass something which has not type Sorted then we will get an MYPY error at compile time. It looks like Haskell, ah? :)