#πŸ”’ How to type a type?

42 messages Β· Page 1 of 1 (latest)

torpid hedge
#

So I have a Figure class which has a dict of properties. These properties are defined by Rules which have a name, type, and an optional default value.
Rule types would either be Figure, str, bool, or int. So, a str rule foo applied to a Figure would then let you do Figure.properties["foo"] to get a str back.
So how do I type that property_type argument of the Rule.init method?
I was considering using an enum but I'd like to just use the types directly (unless this is not a good idea, what do you think I should do?)

Thanks

wind larkBOT
#

@torpid hedge

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

stoic marsh
#

oh wait hold on lemme read the rest of the post

stoic marsh
#

that's correct?

torpid hedge
#

Not quite what I meant

#

one sec

stoic marsh
#

ok no problem

torpid hedge
#
class Figure:
  properties: dict[str, Figure | str | bool | int]

class Rule:
  name: str
  rule_type: ??? # what do I put here?

test_rule = Rule('test', ???)
test_fig.apply_rule('test', value of type rule_type)
test_fig.properties['test'] # This will be type rule_type
#

When I prompt the user for the value it would accept a str, an int, a bool, etc.

#

depending on that rules type

misty copper
#

Maybe Literal?

#

an enum may help too

#

!d enum.Enum

wind larkBOT
#

class enum.Enum```
*Enum* is the base class for all *enum* enumerations.
torpid hedge
#

I was thinking of using an enum but IDK if its the best option

#

is it what you would do?

torpid silo
#

What is enum

#

!d enum

wind larkBOT
torpid silo
#

Hmm

#

No description

#

Sad

torpid hedge
#

theres an example there

#

they are pretty cool

torpid silo
#

Ty

stoic marsh
#

either rule_type: type OR ```py
type RuleType = Figure | ...

class Rule:
name: str
type: RuleType

torpid hedge
stoic marsh
misty copper
#

It might be better to use a tagged union or even generics

stoic marsh
#

the type union would probably be either

#

because you can reuse it in your dict[str, <rule type here>]

torpid hedge
#

okay, thanks a lot!

stoic marsh
#

no problem thumbsup

#

!close to close the post

torpid hedge
#

!close

wind larkBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.