Question: `make_class` equivalent of the "new API" - defining fields using type annotations

Open
#869 1 comment 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
25/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
python
Domain
tooling

Research direction

Start by examining attr.make_class with the supplied inspect.get_annotations example, including the frozen=True, on_setattr=True, and auto_attribs=True options. Determine whether the requested programmatic equivalent is supported or needs a documented change, and verify the result against the behavior of attr.frozen(Test).

Written by the indexing model from the issue text.

Description

Feature

I have been trying to use attr.make_class to create a class based on type annotations. This is exemplified by the following code:

import attr
import inspect

class Test:
    a: int
    b: str

aTest = attr.frozen(Test)

sig = inspect.get_annotations(Test)
print(sig) # {"a": int, "b": str}

# fails with AttributeError: type object 'int' has no attribute 'type'
bTest = attr.make_class("Test", sig, frozen=True, on_setattr=True, auto_attribs=True)

The intent were for bTest to be equivalent to aTest, but generated programatically. However, that doesn't seem to work. What is the standard way to create an attr class programmatically from type annotations?

Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python-attrs/attrs

All issues in python-attrs/attrs

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.