python / python/typing

Monkey patching support

Open
#718 7 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

These are just some not terribly well though out ideas about possible monkey support in typing. This would need a proper PEP if it was ever implemented, but I just want to record my ideas here:

# foo accepts a date object, but allows to add and access
# unknown attributes at runtime. It basically treats date
# as having __getattr__()/__setattr__() methods.
def foo(date: Dynamic[datetime.date]) -> None:
    date.my_attr = 123
    print(date.added_by_called)


# typing.dynamic() is a no-op at runtime and basically an alias
# for cast(Generic[X], y) at type-check time, where X is the
# type of y.
# In this example, dt has type Dynamic[datetime.date].
dt = dynamic(datetime.date.today())
foo(dt)

# The following would also work:
foo(datetime.date.today())
other_dt: datetime.date = dt

A possible extensions would be to define the allowed monkey-patched attributes. Something like:

class Monkey(Protocol):
    donkey: int

def foo(dt: Dynamic[datetime.date, Monkey]) -> None:
    # ok:
    print(dt.year)
    dt.donkey += 3
    # errors:
    print(dt.kong)
    dt.donkey += ""

dt = dynamic(datetime.date.today(), Monkey)

Contributor guide

No contributing guide indexed for this repository

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.

Research direction

Start by reviewing the proposed Dynamic and dynamic examples, including the Protocol-based allowed-attributes extension, then read the seven-comment discussion for constraints or objections. This issue is exploratory rather than implementation-ready; done would require an agreed design and the proper PEP mentioned in the issue before code work can begin.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.