I'm working on a project where I've defined a number of NewType types to represent various identifiers, so that they can't be accidentally mingled together.
from typing import NewType
UserId = NewType('UserId', int)
Although this has brought the benefits mentioned above, there are cases where it has been frustrating. For server routes that accept these identifiers as arguments in the query string, the process of converting to the required type seems needlessly tedious.
@app.get('/some_route')
def some_route():
user = UserId(int(request.args['user_id']))
Is there a way I can cleanly use the default int constructor when initialising a UserId. I'm looking for syntax as clean as the following, but without the complexity of needing to create a class for each type?
@app.get('/some_route')
def some_route():
# The conversion from str to int is performed behind the scenes automatically
user = UserId(request.args['user_id'])
Ok so it turns out that I overlooked the simplest solution: just use a subclass.
In this case, the type is created using
class UserId(int):
pass
Note that this does have the performance drawbacks associated with creating a subclass, however.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With