ahawker / ulid

Universally Unique Lexicographically Sortable Identifier (ULID) in Python 3
Apache License 2.0
695 stars 42 forks source link

API: Add from_* style method #313

Closed ahawker closed 5 years ago

ahawker commented 5 years ago

Currently, the API exposes multiple methods for creating ulid.ULID instances from other data types. However, it does not support a "catch all" call that attempts to make the determination based on type and requires the caller to do that.

Let's imagine that a user of the library has read an input value from somewhere that they have a relatively high confidence is a ULID. However, they don't know the format in which it was stored. In order to support this mechanism, the user of the library needs to write the following code:

if isinstance(value, bytes):
    return ulid.from_bytes(value)
if isinstance(value, int):
    return ulid.from_int(value)
if isinstance(value, str):
    return ulid.from_str(value)
if isinstance(value, uuid.UUID):
    return ulid.from_uuid(value)

raise ValueError('Cannot create ULID from type {}'.format(value.__class__.__name__) 

This is pretty verbose, especially since we could hide this logic inside the library in a separate API call itself. It will be slightly slower that calling the correct method directly, since we have to run the if/else tree every time and don't know the "hot path", but should be helpful for this scenario.

Potential thoughts:

ahawker commented 5 years ago

Reopening issue as #314 was incomplete to address this issue.