Skip to content

Can't figure out the syntax for Optional[T] to use with dataclasses #2536

Answered by scauligi
vidjuheffex asked this question in Q&A
Discussion options

You must be logged in to vote

hy --spy (or hy2py) is your friend!
The #^ macro doesn't generate an assignment, it's just the annotation; you still need a setv. So your current Hy code declares a field myattr with no assignment, followed by a standalone expression None:

# => (defclass [dataclass] MyClass []
# ...   "A dataclass to hold round information"
# ...   #^ (of Optional int) myattr None)
@dataclass
class MyClass:
    """A dataclass to hold round information"""
    myattr: Optional[int]
    None

You probably want this:

(defclass [dataclass] MyClass []
  (setv #^ (of Optional int) myattr None))

which translates to this:

@dataclass
class MyClass:
    myattr: Optional[int] = None

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
2 replies
@vidjuheffex
Comment options

@Kodiologist
Comment options

Comment options

You must be logged in to vote
1 reply
@vidjuheffex
Comment options

Answer selected by Kodiologist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants