René's URL Explorer Experiment


Title: Simplifying the implementation of signature-overloaded functions · Issue #7966 · matplotlib/matplotlib · GitHub

Open Graph Title: Simplifying the implementation of signature-overloaded functions · Issue #7966 · matplotlib/matplotlib

X Title: Simplifying the implementation of signature-overloaded functions · Issue #7966 · matplotlib/matplotlib

Description: There are many functions in matplotlib that have "interesting" call signatures, e.g. that could be called with 1, 2 or 3 arguments with different semantics (i.e. not just binding arguments in order and having defaults for the later ones)...

Open Graph Description: There are many functions in matplotlib that have "interesting" call signatures, e.g. that could be called with 1, 2 or 3 arguments with different semantics (i.e. not just binding arguments in order...

X Description: There are many functions in matplotlib that have "interesting" call signatures, e.g. that could be called with 1, 2 or 3 arguments with different semantics (i.e. not just binding argument...

Opengraph URL: https://github.com/matplotlib/matplotlib/issues/7966

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Simplifying the implementation of signature-overloaded functions","articleBody":"There are many functions in matplotlib that have \"interesting\" call signatures, e.g. that could be called with 1, 2 or 3 arguments with different semantics (i.e. not just binding arguments in order and having defaults for the later ones).  In this case, the binding of arguments is typically written on an ad-hoc basis, with some bugs (e.g. the one I fixed in https://github.com/matplotlib/matplotlib/pull/7859/files#diff-84224cb1c8cd1f13b7adc5930ee2fc8fR365) or difficult to read code (e.g. https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/quiver.py#L374 (`quiver._parse_args`)).\r\n\r\nMoreover, there are also cases where a function argument should be renamed, but cannot be due to backwards compatibility considerations (e.g. https://github.com/matplotlib/matplotlib/issues/7954).\r\n\r\nI propose to fix both issues using a signature-overloading decorator (see below for prototype implementation).  Basically, the idea would be to write something like\r\n```\r\n@signature_dispatch\r\ndef func(\u003cinner_signature\u003e): ... # inner function definition\r\n\r\n@func.overload\r\ndef func(\u003csignature_1\u003e):\r\n    # \u003cplay with args until they match inner_signature\u003e\r\n    return func.__wrapped__(\u003cnew_args\u003e)  # Refers to the \"inner\" function\r\n\r\n@func.overload\r\ndef func(\u003csignature_2\u003e):\r\n    # \u003cplay with args until they match inner_signature\u003e\r\n    return func.__wrapped__(\u003cnew_args\u003e)  # Refers to the \"inner\" function\r\n```\r\nwhere the first overload that can bind the arguments is the one used.\r\n\r\nIn order to support changes in signature due to argument renaming, an overload with the previous signature that raises a DeprecationWarning before forwarding the argument to the \"inner\" function can be used.\r\n\r\nThoughts?\r\n\r\nProtoype implementation:\r\n\r\n```\r\n\"\"\"A signature dispatch decorator.\r\n\r\nDecorate a function using::\r\n\r\n    @signature_dispatch\r\n    def func(...):\r\n        ...\r\n\r\nand provide signature overloads using::\r\n\r\n    @func.overload\r\n    def func(...): # Note the use of the same name.\r\n        ...\r\n        # Refer to the \"original\" function as ``func.__wrapped__``\r\n\r\nCalling the function will try binding the arguments passed to each overload in\r\nturn, until one binding succeeds; that overload will be called and its return\r\nvalue (or raised Exception) be used for the original function call.\r\n\r\nOverloads can define keyword-only arguments in trailing position in a Py2\r\ncompatible manner by having a marker argument named ``__kw_only__``; that\r\nargument behaves like \"*\" in Py3, i.e., later arguments become keyword-only\r\n(and the ``__kw_only__`` argument itself is always bound to None).\r\n\r\nOverloads can define positional arguments in leading position (as defined in\r\nhttps://docs.python.org/3/library/inspect.html#inspect.Parameter.kind) by\r\nhaving a marker argument named ``__pos_only__``; earlier arguments become\r\npositional-only (and the ``__pos_only__`` argument iself is always bound to\r\nNone).\r\n\r\nThis implementation should be compatible with Py2 as long as a backport of the\r\nsignature object (e.g. funcsigs) is used instead.\r\n\"\"\"\r\n\r\n\r\nfrom collections import OrderedDict\r\nfrom functools import wraps\r\nfrom inspect import signature\r\n\r\n\r\ndef signature_dispatch(func):\r\n\r\n    def overload(impl):\r\n        sig = signature(impl)\r\n        params = list(sig.parameters.values())\r\n        try:\r\n            idx = next(idx for idx, param in enumerate(params)\r\n                       if param.name == \"__pos_only__\")\r\n        except ValueError:\r\n            pass\r\n        else:\r\n            # Make earlier parameters positional only, skip __pos_only__ marker.\r\n            params = ([param.replace(kind=param.POSITIONAL_ONLY)\r\n                       for param in params[:idx]]\r\n                      + params[idx + 1:])\r\n        try:\r\n            idx = next(idx for idx, param in enumerate(params)\r\n                       if param.name == \"__kw_only__\")\r\n        except ValueError:\r\n            pass\r\n        else:\r\n            # Make later parameters positional only, skip __kw_only__ marker.\r\n            params = (params[:idx]\r\n                      + [param.replace(kind=param.KEYWORD_ONLY)\r\n                         for param in params[idx + 1:]]\r\n\r\n        sig = sig.replace(parameters=params)\r\n        impls_sigs.append((impl, sig))\r\n        return wrapper\r\n\r\n    @wraps(func)\r\n    def wrapper(*args, **kwargs):\r\n        for impl, sig in impls_sigs:\r\n            try:\r\n                ba = sig.bind(*args, **kwargs)\r\n            except TypeError:\r\n                continue\r\n            else:\r\n                if \"__pos_only__\" in signature(impl).parameters:\r\n                    ba.arguments[\"__pos_only__\"] = None\r\n                return impl(**ba.arguments)\r\n        raise TypeError(\"No matching signature\")\r\n\r\n    impls_sigs = []\r\n    wrapper.overload = overload\r\n    return wrapper\r\n\r\n\r\n@signature_dispatch\r\ndef slice_like(x, y, z):\r\n    return slice(x, y, z)\r\n\r\n@slice_like.overload\r\ndef slice_like(x, __pos_only__):\r\n    return slice_like.__wrapped__(None, x, None)\r\n\r\n@slice_like.overload\r\ndef slice_like(x, y, __pos_only__):\r\n    return slice_like.__wrapped__(x, y, None)\r\n\r\n@slice_like.overload\r\ndef slice_like(x, y, z, __pos_only__):\r\n    return slice_like.__wrapped__(x, y, z)\r\n\r\nassert slice_like(10) == slice(10)\r\nassert slice_like(10, 20) == slice(10, 20)\r\nassert slice_like(10, 20, 30) == slice(10, 20, 30)\r\ntry: slice_like(x=10)\r\nexcept TypeError: pass\r\nelse: assert False\r\n```","author":{"url":"https://github.com/anntzer","@type":"Person","name":"anntzer"},"datePublished":"2017-01-28T01:11:18.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":5},"url":"https://github.com/7966/matplotlib/issues/7966"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:2e9e922b-b5b2-891a-8002-970cb3e9b3e6
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idBA40:1B675D:29040D3:37EFF30:6A53BD6A
html-safe-noncea7136eef69c248f61f161a4cc4033c4250ed97e07d2eb6585ee48500da45d0c1
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCQTQwOjFCNjc1RDoyOTA0MEQzOjM3RUZGMzA6NkE1M0JENkEiLCJ2aXNpdG9yX2lkIjoiNjgwOTU4ODA1MzA3NTgwMzQ5OSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmacd2a83d8c1a5c5613e998a85b146e2836e2a0bd936a6e112757aaab5d2783936f
hovercard-subject-tagissue:203776892
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/matplotlib/matplotlib/7966/issue_layout
twitter:imagehttps://opengraph.githubassets.com/bc1e72e4235a7187d58578814c1e622690f473aa43a936072bedc85499322ec6/matplotlib/matplotlib/issues/7966
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/bc1e72e4235a7187d58578814c1e622690f473aa43a936072bedc85499322ec6/matplotlib/matplotlib/issues/7966
og:image:altThere are many functions in matplotlib that have "interesting" call signatures, e.g. that could be called with 1, 2 or 3 arguments with different semantics (i.e. not just binding arguments in order...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameanntzer
hostnamegithub.com
expected-hostnamegithub.com
Noneb9a586c06a05a7a86fc7e3f4dbd03e42f6869085879aa184aa6369456dbd50fb
turbo-cache-controlno-preview
go-importgithub.com/matplotlib/matplotlib git https://github.com/matplotlib/matplotlib.git
octolytics-dimension-user_id215947
octolytics-dimension-user_loginmatplotlib
octolytics-dimension-repository_id1385122
octolytics-dimension-repository_nwomatplotlib/matplotlib
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id1385122
octolytics-dimension-repository_network_root_nwomatplotlib/matplotlib
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release07a982c1d40157c619b364352b704c3ce66bb332
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/matplotlib/matplotlib/issues/7966#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmatplotlib%2Fmatplotlib%2Fissues%2F7966
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub Copilot appDirect agents from issue to mergehttps://github.com/features/ai/github-app
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
View all resourceshttps://github.com/resources
GitHub SponsorsFund open source developershttps://github.com/open-source/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/open-source/accelerator
GitHub Starshttps://stars.github.com
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmatplotlib%2Fmatplotlib%2Fissues%2F7966
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=matplotlib%2Fmatplotlib
Reloadhttps://github.com/matplotlib/matplotlib/issues/7966
Reloadhttps://github.com/matplotlib/matplotlib/issues/7966
Reloadhttps://github.com/matplotlib/matplotlib/issues/7966
Please reload this pagehttps://github.com/matplotlib/matplotlib/issues/7966
matplotlib https://github.com/matplotlib
matplotlibhttps://github.com/matplotlib/matplotlib
Please reload this pagehttps://github.com/matplotlib/matplotlib/issues/7966
Notifications https://github.com/login?return_to=%2Fmatplotlib%2Fmatplotlib
Fork 8.4k https://github.com/login?return_to=%2Fmatplotlib%2Fmatplotlib
Star 23k https://github.com/login?return_to=%2Fmatplotlib%2Fmatplotlib
Code https://github.com/matplotlib/matplotlib
Issues 1.1k https://github.com/matplotlib/matplotlib/issues
Pull requests 408 https://github.com/matplotlib/matplotlib/pulls
Actions https://github.com/matplotlib/matplotlib/actions
Projects https://github.com/matplotlib/matplotlib/projects
Wiki https://github.com/matplotlib/matplotlib/wiki
Security and quality 0 https://github.com/matplotlib/matplotlib/security
Insights https://github.com/matplotlib/matplotlib/pulse
Code https://github.com/matplotlib/matplotlib
Issues https://github.com/matplotlib/matplotlib/issues
Pull requests https://github.com/matplotlib/matplotlib/pulls
Actions https://github.com/matplotlib/matplotlib/actions
Projects https://github.com/matplotlib/matplotlib/projects
Wiki https://github.com/matplotlib/matplotlib/wiki
Security and quality https://github.com/matplotlib/matplotlib/security
Insights https://github.com/matplotlib/matplotlib/pulse
Simplifying the implementation of signature-overloaded functionshttps://github.com/matplotlib/matplotlib/issues/7966#top
https://github.com/anntzer
anntzerhttps://github.com/anntzer
on Jan 28, 2017https://github.com/matplotlib/matplotlib/issues/7966#issue-203776892
https://github.com/matplotlib/matplotlib/pull/7859/files#diff-84224cb1c8cd1f13b7adc5930ee2fc8fR365https://github.com/matplotlib/matplotlib/pull/7859/files#diff-84224cb1c8cd1f13b7adc5930ee2fc8fR365
https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/quiver.py#L374https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/quiver.py#L374
#7954https://github.com/matplotlib/matplotlib/issues/7954
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.