Skip to content

Provide a way to reference current class for intstance methods #95

Open

Description

@dluciv

Imagine following:

class MyDummyNumber:
    ...
    @dispatch(int)
    def __add__(self, i):
        ...

    @dispatch(MyDummyNumber)
    def __add__(self, m):
        ...

As expected, we have NameError: name 'MyDummyNumber' is not defined here, which is not multipledispatch issue, but Python one.

There are many ugly ways to workaround this. Then beautiful way is needed!

However multipledispatch works during runtime, so I think that it is potentially possible to specify "current class" during dispatching definition, like following:

    @dispatch(multipledispatch.current_class)
    def __add__(self, m):
        ...

Activity

  1. changed the title [-]Suggest a way to reference current class for intstance methods[/-] [+]Provide a way to reference current class for intstance methods[/+] on Nov 17, 2018
  2. francesco-ballarin commented on Nov 17, 2018

    @francesco-ballarin
    Contributor

    This is supported in my patched version at #78 through lambda functions. No agreement has been reached on possible integration. Have a look if that could be helpful.

  3. dluciv commented on Nov 17, 2018

    @dluciv
    Author

    A great way as for me, waiting to get it in new releases. Thank you!

    May be it is even useful to define identical function inside multidispatch module, as Python lacks built-in one.

  4. Mystic-Mirage commented on May 10, 2019

    @Mystic-Mirage
    Contributor

    I've tried to solve this in my PR #100

  5. lucag commented on Dec 27, 2022

    @lucag

    Just ran into the same problem. Any progress on this?

    @Mystic-Mirage's PR seems to be consistent with annotations currently in use, which employ stringified type names when a forward declaration is needed. So in the case of @dluciv's example, one would simply write

    class MyDummyNumber:
        ...
        @dispatch(int)
        def __add__(self, i):
            ...
    
        @dispatch('MyDummyNumber')
        def __add__(self, m):
            ...

    Another possible solution would be to use the Self type introduced by PEP 673, but that also does not work with the current implementation of multipledispatch.

  6. Mystic-Mirage commented on Dec 27, 2022

    @Mystic-Mirage
    Contributor

    There is another way to fix this by adding support for from __future__ import annotations introduced in PEP 563

    Currently, it breaks multipledispatch completely but looks promising.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions