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

gh-98169 dataclasses.astuple support DefaultDict #98170

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

kwsp
Copy link
Contributor

@kwsp kwsp commented Oct 11, 2022

Basically applying the same fix for asdict from #32056 to astuple. These two should've been the same PR, but I didn't know about astuple previously.

Also modified the handling of DefaultDict in asdict a little so that we only call isinstance(obj, dict) once. This results in a ~3% speed up on my machine on this example:

# benchmark
from dataclasses import dataclass, asdict
from collections import defaultdict
from typing import DefaultDict, Dict, List, NamedTuple
import time


class NT(NamedTuple):
    x: int
    y: float

@dataclass
class C:
    dd: DefaultDict[str, List]
    nt: NT
    d1: Dict[str, List]
    d2: Dict[str, int]

def get_instance():
    instance = C(dd=defaultdict(list), nt=NT(1, 1.), d1={}, d2={})
    instance.dd["x"].append(12)
    instance.dd["x"].append(13)
    instance.d1["y"] = [1, 2, 3]
    instance.d2["z"] = 1
    return instance

instance = get_instance()

def timeit(callable, n_runs = 100_000, name=""):
    t1 = time.perf_counter_ns()
    for _ in range(n_runs):
        callable()

    elapsed_ms = round(1e-6 * (time.perf_counter_ns() - t1), 2)
    print(f"{name}\t{n_runs} runs: {elapsed_ms} ms")

timeit(lambda: asdict(instance), name="asdict")
timeit(lambda: astuple(instance), name="astuple")

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

Successfully merging this pull request may close these issues.

None yet

2 participants