ahawker / ulid

Universally Unique Lexicographically Sortable Identifier (ULID) in Python 3

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

API: Add from_* style method

ahawker opened this issue · comments

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:

  • from_(value)
  • from_value(value)
  • from_obj(value)
  • from_unknown(value)
  • parse(value)
  • decode(value)
  • load(value)

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

  • Add documentation to README for parse method.
  • Expose parse method via module interface.
  • Add tests for the module interface so I don't make this mistake again.