quicktype icon indicating copy to clipboard operation
quicktype copied to clipboard

Python Support

Open dvdsgl opened this issue 9 years ago • 20 comments

dvdsgl avatar Sep 22 '17 23:09 dvdsgl

I'm also interested in this feature. I haven't done much TypeScript, but this feature would really help me at my day job, so I'm considering contributing in this area. I'm unable to start this until #291 is resolved.

dagrooms52 avatar Nov 27 '17 04:11 dagrooms52

@dagrooms52 Are you still on this? Is there anything we can do to help?

schani avatar Dec 31 '17 23:12 schani

@ianleatherbury is also interested in working on Python support but doesn't think he'll be able to contribute for a couple of months.

dvdsgl avatar Dec 31 '17 23:12 dvdsgl

Yup, still nailing down my schedule for the New Year right now. I should have a better idea of a timeline in the next couple of weeks.

IanLeatherbury avatar Jan 01 '18 00:01 IanLeatherbury

Last thing I did before the holidays was start testing, it looked like the renderer API breaking changes had broken a few things for my Python renderer layer so I decided to wait for the dust to clear. Is the API feeling more stable now? I don't think I'll be able to hammer through fixing the breaking changes and testing fast enough to not get broken by the next API changes otherwise. I can only give it about an hour every night.

dagrooms52 avatar Jan 03 '18 18:01 dagrooms52

Sorry about that. Just keep targeting whichever quicktype commit you're on now, and once you have it somewhat working I'll just adapt it to the latest changes. I've been doing that a lot - I'm pretty efficient at it ;-)

schani avatar Jan 03 '18 18:01 schani

@IanLeatherbury How's it going?

schani avatar Feb 20 '18 17:02 schani

Am hopefully about to finish emitting classes today. I think the implementation is pretty simplistic, and I'm not sure exactly what you guys need in terms of tests, but, I can submit a PR soon and we can find out :-)

IanLeatherbury avatar Feb 20 '18 17:02 IanLeatherbury

I can help you set up the tests - it's pretty easy. The main thing you need is a "driver" file, which is basically a simple Python command line program that uses the code you emit to deserialize some input JSON and then to serialize it back to JSON.

This is the driver for C#, for example: https://github.com/quicktype/quicktype/blob/master/test/fixtures/csharp/Program.cs

You can take the filename from the command line arguments, or you can read from stdin - it doesn't matter.

schani avatar Feb 20 '18 17:02 schani

Ah gotcha, yeah that seems pretty simple. I'm going to finish the FromJson side today, I still need to take a look at the ToJson side though.

IanLeatherbury avatar Feb 20 '18 17:02 IanLeatherbury

Any news? - Really could be a useful language output 👍

SamuelMarks avatar Mar 25 '18 06:03 SamuelMarks

Sady, I'm not going to finish this anytime soon. I've had some work projects come up that are taking up my weekend coding time. Anyone else want to give it a shot?

IanLeatherbury avatar Mar 26 '18 14:03 IanLeatherbury

@IanLeatherbury Yeah I should have a chance next weekend. Send/link me your WiP?

SamuelMarks avatar Mar 26 '18 14:03 SamuelMarks

Yep, you can find the repo here in the Python branch.

The typescript file to do the transformation is here.

I was working with Mark on this in the Quicktype slack channel and he was very helpful.

Also note, this is from an earlier version of Quicktype, so some things have changed since I began implementing it, so if you pull the latest master from the main repo, I imagine some things will break :-)

IanLeatherbury avatar Mar 26 '18 14:03 IanLeatherbury

@dagrooms52 had also started a Python effort - his code produces nice type annotations: https://github.com/quicktype/quicktype/compare/master...dagrooms52:python-lang

schani avatar Mar 26 '18 15:03 schani

Breaking changes kind of killed my efforts (plus first release at my day job, fun!) so I don't think my branch will be extremely usable, but maybe some of it can be helpful like the type annotation bits.

dagrooms52 avatar Mar 26 '18 18:03 dagrooms52

@SamuelMarks What's the status? Do you need help?

schani avatar Apr 12 '18 14:04 schani

@schani Haven't had the chance to look at it since I got that Node.js memory solution off your Slack. Been busy with my research.

Should have time this weekend to work on it, would welcome input 🙂

SamuelMarks avatar Apr 12 '18 15:04 SamuelMarks

@SamuelMarks I suggest figuring out exactly what the code is you want quicktype to generate first, and then actually making quicktype produce it isn't all that hard anymore, and we can help you with that on Slack, and you can look at existing target languages that do something similar.

schani avatar Apr 12 '18 15:04 schani

I'm taking this over. Hand-coded draft of the code I'd like to generate:

from typing import List, Optional, TypeVar, Any, Callable, Dict, Iterable, Union
from enum import Enum

T = TypeVar("T")


def from_str(x: Any) -> str:
    assert isinstance(x, str)
    return x


def from_int(x: Any) -> int:
    assert isinstance(x, int)
    return x


def from_float(x: Any) -> float:
    assert isinstance(x, (float, int))
    return float(x)


def from_list(f: Callable[[Any], T], x: Any) -> List[T]:
    assert isinstance(x, list)
    return [f(y) for y in x]


def from_optional(f: Callable[[Any], T], obj: Dict[Any, Any], key: str) -> Optional[T]:
    if key not in obj:
        return None
    x = obj[key]
    if x is None:
        return None
    return f(x)


def from_union(fs: Iterable[Callable[[Any], T]], x: Any) -> T:
    for f in fs:
        try:
            return f(x)
        except AssertionError:
            pass
    assert False


class Egg(Enum):
    NOT_IN_EGGS = "Not in Eggs"
    OMANYTE_CANDY = "Omanyte Candy"
    THE_10KM = "10 km"
    THE_2KM = "2 km"
    THE_5KM = "5 km"


class Evolution:
    num: str
    name: str

    def __init__(self, obj) -> None:
        assert isinstance(obj, dict)
        self.num = from_str(obj["num"])
        self.name = from_str(obj["name"])


class Weakness(Enum):
    BUG = "Bug"
    DARK = "Dark"
    DRAGON = "Dragon"
    ELECTRIC = "Electric"
    FAIRY = "Fairy"
    FIGHTING = "Fighting"
    FIRE = "Fire"
    FLYING = "Flying"
    GHOST = "Ghost"
    GRASS = "Grass"
    GROUND = "Ground"
    ICE = "Ice"
    POISON = "Poison"
    PSYCHIC = "Psychic"
    ROCK = "Rock"
    STEEL = "Steel"
    WATER = "Water"


class Pokemon:
    id: int
    num: str
    name: str
    img: str
    type: List[str]
    height: str
    weight: str
    candy: str
    candyCount: Optional[int]
    egg: Egg
    spawnChance: float
    avgSpawns: float
    spawnTime: str
    multipliers: Optional[List[float]]
    weaknesses: List[Weakness]
    nextEvolution: Optional[List[Evolution]]
    prevEvolution: Optional[List[Evolution]]

    def __init__(self, obj) -> None:
        assert isinstance(obj, dict)
        self.id = from_int(obj["id"])
        self.num = from_str(obj["num"])
        self.name = from_str(obj["name"])
        self.img = from_str(obj["img"])
        self.type = from_list(from_str, obj["type"])
        self.height = from_str(obj["height"])
        self.weight = from_str(obj["weight"])
        self.candy = from_str(obj["candy"])
        self.candyCount = from_optional(from_int, obj, "candy_count")
        self.egg = Egg(obj["egg"])
        self.spawnChance = from_float(obj["spawn_chance"])
        self.avgSpawns = from_float(obj["avg_spawns"])
        self.spawnTime = from_str(obj["spawn_time"])
        self.multipliers = from_optional(
            lambda x: from_list(from_float, x), obj, "multipliers")
        self.weaknesses = from_list(Weakness, obj["weaknesses"])
        self.nextEvolution = from_optional(
            lambda x: from_list(Evolution, x), obj, "next_evolution")
        self.prevEvolution = from_optional(
            lambda x: from_list(Evolution, x), obj, "prev_evolution")


class TopLevel:
    pokemon: List[Pokemon]

    def __init__(self, obj) -> None:
        assert isinstance(obj, dict)
        self.pokemon = from_list(Pokemon, obj["pokemon"])

I'm having problems with typing unions.

schani avatar Jun 27 '18 15:06 schani