Transcrypt
Transcrypt copied to clipboard
@dataclass failes to compile without default values for members
This code compiles :
from dataclasses import dataclass
@dataclass
class Foo :
bar : str = 'bar'
And this doesnt :
from dataclasses import dataclass
@dataclass
class Foo :
bar : str
hello.py:
from dataclasses import dataclass
@dataclass
class Foo:
bar: str = 'bar'
def greet():
f = Foo('baz')
document.getElementById('greet').innerHTML = str(f)
index.html:
<script type="module">
import * as hello from './__target__/hello.js';
window.hello = hello;
</script>
<h2>Demo</h2>
<div id="greet">...</div>
<button onclick="hello.greet()">Greet</button>
Even with compilation, I'm not sure dataclasses will run correctly. The exepctation I have is that str(f) will return Foo(bar='baz'). I still see ..., though.
I really believe dataclasses and type annotation are going to be a big deal in Python over time.
I just wanted to +1 this issue. Dataclasses are a major reason I would want to run Python in the browser. The current implementation in Transcrypt is a step in the right direction, but still too shallow to use. Here are a few of my troubles:
- dataclasses must not require default values for variables, that goes totally against their spirit and usefulness.
- dataclasses.field() not implemented! "import not found: field"
- The most useful things in the typing module are not implemented, so your dataclasses are difficult to write if you want variables with types including Dict, List, Optional, Union, Sequence etc.
- Frozen dataclasses not implemented. @dataclass(frozen=True) has no effect.
- dataclasses.asdict() not implemented. (I believe it's not useful in JS but important to share code between client and server.)
I've found asdict to be excellent as a named parameter input where the dataclass itself could mirror a specific API.
For example:
from dataclasses import asdict, dataclass
@dataclass
class Bar:
a: int = 1
b: str = '2'
c: float = 3.0
def foo(a: int, b: str, c: float):
...
x = Bar()
foo(**asdict(x))
I'm not sure how well that would translate with Transcrypt, but I've found that the pattern is useful in both testing and (de)serialization.
I was wanting to use dataclasses as a way to document props for React components, but not being able to use them without default values does make it less appealing.