Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Literal type usage #11

Open
martin-thoma opened this issue Jul 21, 2021 · 3 comments
Open

Literal type usage #11

martin-thoma opened this issue Jul 21, 2021 · 3 comments

Comments

@martin-thoma
Copy link
Contributor

The Literal type was introduced with PEP 586 in Python 3.8 and can be used with Pydantic. With typing-extensions the Literal type can also be used in Python 3.6+.

Would it be ok to introduce Literal?

@overcat
Copy link
Member

overcat commented Jul 21, 2021

Hi, I just checked out PEP-586, can you tell me where you plan to introduce it?

Thank you.

@martin-thoma
Copy link
Contributor Author

Here: https://github.com/StellarCN/stellar-model/blob/main/stellar_model/model/horizon/operations.py#L133-L134

asset_type: Literal["native", "credit_alphanum4", "credit_alphanum12"]
type: Literal["payment"]
type_i: Literal[1]

I'm uncertain why type and type_i are not part of the model, but at least for asset_type it makes sense.

@overcat
Copy link
Member

overcat commented Jul 21, 2021

I think using Enum is a better choice here.

from enum import Enum

from pydantic import BaseModel

class AssetType(Enum):
    native = "native"
    credit_alphanum4 = "credit_alphanum4"
    credit_alphanum12 = "credit_alphanum12"


class DemoOp(BaseModel):
    asset_type: AssetType

demo_op = DemoOp.parse_obj({'asset_type': 'credit_alphanum4'})
assert demo_op.asset_type == AssetType.credit_alphanum4
# If we use Literal here, the user still has to compare strings here
# assert demo_op.asset_type == 'credit_alphanum4'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants