René's URL Explorer Experiment


Title: Proposal: syntax for variable and attribute annotations (PEP 526) · Issue #258 · python/typing · GitHub

Open Graph Title: Proposal: syntax for variable and attribute annotations (PEP 526) · Issue #258 · python/typing

X Title: Proposal: syntax for variable and attribute annotations (PEP 526) · Issue #258 · python/typing

Description: Introduction This issue is reserved for substantive work on PEP 526, "Syntax for Variable and Attribute Annotations". For textual nits please comment directly on the latest PR for this PEP in the peps repo. I sent a strawman proposal to ...

Open Graph Description: Introduction This issue is reserved for substantive work on PEP 526, "Syntax for Variable and Attribute Annotations". For textual nits please comment directly on the latest PR for this PEP in the p...

X Description: Introduction This issue is reserved for substantive work on PEP 526, "Syntax for Variable and Attribute Annotations". For textual nits please comment directly on the latest PR for this PE...

Opengraph URL: https://github.com/python/typing/issues/258

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Proposal: syntax for variable and attribute annotations (PEP 526)","articleBody":"## Introduction\n\nThis issue is reserved for substantive work on [PEP 526](https://www.python.org/dev/peps/pep-0526/), \"Syntax for Variable and Attribute Annotations\". For textual nits please comment directly on the latest PR for this PEP in the [peps repo](https://github.com/python/peps).\n\nI sent a [strawman proposal](https://mail.python.org/pipermail/python-ideas/2016-August/041294.html) to python-ideas. The feedback was mixed but useful -- people tried to poke holes in it from many angles.\n\nIn this issue I want to arrive at a more solid specification. I'm out of time right now, but here are some notes:\n- Class variables vs. instance variables\n- Specify instance variables in class body vs. in `__init__` or `__new__`\n- Thinking with your runtime hat on vs. your type checking hat\n- Importance of `a: \u003ctype>` vs. how it strikes people the wrong way\n- Tuple unpacking is a mess, let's avoid it entirely\n- Collecting the types in something similar to `__annotations__`\n- Cost of doing that for locals\n- Cost of introducing a new keywords\n### Work in progress here!\n\nI'm updating the issue description to avoid spamming subscribers to this tracker. I'll keep doing this until we have reasonable discussion.\n## Basic proposal\n\nMy basic observation is that introducing a new keyword has two downsides: (a) choice of a good keyword is hard (e.g. it can't be 'var' because that is way too common a variable name, and it can't be 'local' if we want to use it for class variables or globals,) and (b) no matter what we choose, we'll still need a `__future__` import.\n\nSo I'm proposing something keyword-free:\n\n``` python\na: List[int] = []\nb: Optional[int] = None\n```\n\nThe idea is that this is pretty easy to explain to someone who's already familiar with function annotations.\n### Multiple types/variables\n\nAn obvious question is whether to allow combining type declarations with tuple unpacking (e.g. `a, b, c = x`). This leads to (real or perceived) ambiguity, and I propose _not_ to support this. If there's a type annotation there can only be one variable to its left, and one value to its right. This still allows tuple _packing_ (just put the tuple in parentheses) but it disallows tuple _unpacking_. (It's been proposed to allow multiple parenthesized variable names, or types inside parentheses, but none of these look attractive to me.)\n\nThere's a similar question about what to about the type of `a = b = c = x`. My answer to this is the same: Let's not go there; if you want to add a type you have to split it up.\n### Omitting the initial value\n\nMy next step is to observe that sometimes it's convenient to decouple the type declaration from the initialization. One example is a variable that is initialized in each branch of a big sequence of `if`/`elif`/etc. blocks, where you want to declare its type before entering the first `if`, and there's no convenient initial value (e.g. `None` is not valid because the type is not `Optional[...]`). So I propose to allow leaving out the assignment:\n\n``` python\nlog: Logger\nif develop_mode():\n    log = heavy_logger()\nelif production_mode():\n    log = fatal_only_logger()\nelse:\n    log = default_logger()\nlog.info(\"Server starting up...\")\n```\n\nThe line `log: Logger` looks a little odd at first but I believe you can get used to it easily. Also, it is again similar to what you can do in function annotations. (However, don't hyper-generalize. A line containing just `log` by itself means something different -- it's probably a `NameError`.)\n\nNote that this is something that you currently can't do with `# type` comments -- you currently have to put the type on the (lexically) first assignment, like this:\n\n``` python\nif develop_mode():\n    log = heavy_logger()  # type: Logger\nelif production_mode():\n    log = fatal_only_logger()  # (No type declaration here!)\n# etc.\n```\n\n(In this particular example, a type declaration may be needed because `heavy_logger()` returns a subclass of `Logger`, while other branches produce different subclasses; in general the type checker shouldn't just compute the common superclass because then a type error would just infer the type `object`.)\n#### What about runtime\n\nSuppose we have `a: int` -- what should this do at runtime? Is it ignored, or does it initialize `a` to `None`, or should we perhaps introduce something new like JavaScript's `undefined`? I feel quite strongly that it should leave `a` uninitialized, just as if the line was not there at all.\n## Instance variables and class variables\n\nBased on working with mypy since last December I feel strongly that it's very useful to be able to declare the types of instance variables in class bodies. In fact this is one place where I find the value-less notation (`a: int`) particularly useful, to declare instance variables that should always be initialized by `__init__` (or `__new__`), e.g. variables whose type is mutable or cannot be `None`.\n\nWe still need a way to declare class variables, and here I propose some new syntax, prefixing the type with a `class` keyword:\n\n``` python\nclass Starship:\n    captain: str                      # instance variable without default\n    damage: int = 0                   # instance variable with default (stored in class)\n    stats: class Dict[str, int] = {}  # class variable with initialization\n```\n\nI do have to admit that this is entirely unproven. PEP 484 and mypy currently don't have a way to distinguish between instance and class variables, and it hasn't been a big problem (though I think I've seen a few mypy bug reports related to mypy's inability to tell the difference).\n## Capturing the declared types at runtime\n\nFor function annotations, the types are captured in the function's `__annotations__` object. It would be an obvious extension of this idea to do the same thing for variable declarations. But where exactly would we store this info? A strawman proposal is to introduce `__annotations__` dictionaries at various levels. At each level, the types would go into the `__annotations__` dict at that same level. Examples:\n\nGlobal variables\n\n``` python\nplayers: Dict[str, Player]\nprint(__annotations__)\n```\n\nThis would print `{'players': Dict[str, Player]}` (where the value is the runtime representation of the type `Dict[str, Player]`).\n\nClass and instance variables:\n\n``` python\nclass Starship:\n    # Class variables\n    hitpoints: class int = 50\n    stats: class Dict[str, int] = {}\n    # Instance variables\n    damage: int = 0\n    shield: int = 100\n    captain: str  # no initial value\nprint(Starship.__annotations__)\n```\n\nThis would print a dict with five keys, and corresponding values:\n\n``` python\n{'hitpoints': ClassVar[int],  # I'm making this up as a runtime representation of \"class int\"\n 'stats': ClassVar[Dict[str, int]],\n 'damage': int,\n 'shield': int,\n 'captain': str\n}\n```\n\nFinally, locals. Here I think we should not store the types -- the value of having the annotations available locally is just not enough to offset the cost of creating and populating the dictionary on each function call.\n\nIn fact, I don't even think that the type expression should be evaluated during the function execution. So for example:\n\n``` python\ndef side_effect():\n    print(\"Hello world\")\ndef foo():\n    a: side_effect()\n    a = 12\n    return a\nfoo()\n```\n\nshould not print anything. (A type checker would also complain that `side_effect()` is not a valid type.)\n\nThis is inconsistent with the behavior of\n\n``` python\ndef foo(a: side_effect()):\n    a = 12\n    return a\n```\n\nwhich _does_ print something (at function definition time). But there's a limit to how much consistency I am prepared to propose. (OTOH for globals and class/instance variables I think that there would be some cool use cases for having the information available.)\n### Effect of presence of `a: \u003ctype>`\n\nThe presence of a local variable declaration without initialization still has an effect: it ensures that the variable is considered to be a local variable, and it is given a \"slot\" as if it was assigned to. So, for example:\n\n``` python\ndef foo():\n    a: int\n    print(a)\na = 42\nfoo()\n```\n\nwill raise `UnboundLocalError`, not `NameError`. It's the same as if the code had read\n\n``` python\ndef foo():\n    if False: a = 0\n    print(a)\n```\n## Instance variables inside methods\n\nMypy currently supports `# type` comments on assignments to instance variables (and other things). At least for `__init__` (and `__new__`, and functions called from either) this seems useful, in case you prefer a style where instance variables are declared in `__init__` (etc.) rather than in the class body.\n\nI'd like to support this, at least for cases that obviously refer to instance variables of `self`. In this case we should probably not update `__annotations__`.\n## What about `global` or `nonlocal`?\n\nWe should not change `global` and `nonlocal`. The reason is that those don't declare new variables, they declare that an existing variable is write-accessible in the current scope. Their type belongs in the scope where they are defined.\n## Redundant declarations\n\nI propose that the Python compiler should ignore duplicate declarations of the same variable in the same scope. It should also not bother to validate the type expression (other than evaluating it when not in a local scope). It's up to the type checker to complain about this. The following nonsensical snippet should be allowed at runtime:\n\n``` python\na: 2+2\nb: int = 'hello'\nif b:\n    b: str\n    a: str\n```\n","author":{"url":"https://github.com/gvanrossum","@type":"Person","name":"gvanrossum"},"datePublished":"2016-08-03T19:02:03Z","url":"https://github.com/python/typing/issues/258"}

react-profiling0
react-import-mapreact,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322
route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:d6f956bf-f51a-b520-ec7f-12b4a0e5c59e
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idCA4E:D064:297A779:387EEFD:6B004A83
html-safe-nonce69a1eac232a00bbbd64a93f7f23569396524f62a54e456eb01951389244a4e9b
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDQTRFOkQwNjQ6Mjk3QTc3OTozODdFRUZEOjZCMDA0QTgzIiwidmlzaXRvcl9pZCI6IjMwODkyMzc1ODU0NDEwODE5ODciLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmacb94decee747298da6a9f072c6059d799871ef1b34cc28b87a9ca466bd8b0cd28
hovercard-subject-tagissue:169207731
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/python/typing/258/issue_layout
twitter:imagehttps://opengraph.githubassets.com/8dbbe88e87f95a6a4f583ec010730a48b6de743069bab57847ac6591ee9a5463/python/typing/issues/258
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/8dbbe88e87f95a6a4f583ec010730a48b6de743069bab57847ac6591ee9a5463/python/typing/issues/258
og:image:altIntroduction This issue is reserved for substantive work on PEP 526, "Syntax for Variable and Attribute Annotations". For textual nits please comment directly on the latest PR for this PEP in the p...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamegvanrossum
hostnamegithub.com
expected-hostnamegithub.com
Nonef9517bf360d46638a1e5e7daee7158842fe5ef43c9000afa0e127564a7c2f39b
turbo-cache-controlno-preview
go-importgithub.com/python/typing git https://github.com/python/typing.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id24604008
octolytics-dimension-repository_nwopython/typing
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id24604008
octolytics-dimension-repository_network_root_nwopython/typing
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
releaseb27c5dde30676028abd5c5fc53ce5c9b625f8281
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/python/typing/issues/258#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Ftyping%2Fissues%2F258
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
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
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://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
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Ftyping%2Fissues%2F258
Sign uphttps://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=python%2Ftyping
Reloadhttps://github.com/python/typing/issues/258
Reloadhttps://github.com/python/typing/issues/258
Reloadhttps://github.com/python/typing/issues/258
pythonhttps://github.com/python
typinghttps://github.com/python/typing
Codehttps://github.com/python/typing
Issues206 (206)https://github.com/python/typing/issues
Pull requests27 (27)https://github.com/python/typing/pulls
Discussionshttps://github.com/python/typing/discussions
Actionshttps://github.com/python/typing/actions
Security and qualityhttps://github.com/python/typing/security
Insightshttps://github.com/python/typing/insights
https://github.com/python/typing
New issuehttps://github.com/login?return_to=https://github.com/python/typing/issues/258
New issuehttps://github.com/login?return_to=https://github.com/python/typing/issues/258
Proposal: syntax for variable and attribute annotations (PEP 526)https://github.com/python/typing/issues/258#top
https://github.com/gvanrossum
gvanrossumhttps://github.com/gvanrossum
on Aug 3, 2016https://github.com/python/typing/issues/258#issue-169207731
PEP 526https://www.python.org/dev/peps/pep-0526/
peps repohttps://github.com/python/peps
strawman proposalhttps://mail.python.org/pipermail/python-ideas/2016-August/041294.html
Nexthttps://github.com/python/typing/issues/258?timeline_page=1
gvanrossumhttps://github.com/gvanrossum
enhancementhttps://github.com/python/typing/issues?q=state%3Aopen%20label%3A%22enhancement%22
on Aug 3, 2016https://github.com/python/typing/issues/258#event-744613692
https://github.com/ilevkivskyi
ilevkivskyihttps://github.com/ilevkivskyi
on Aug 4, 2016https://github.com/python/typing/issues/258#issuecomment-237672032
https://github.com/gvanrossum
gvanrossumhttps://github.com/gvanrossum
on Aug 4, 2016https://github.com/python/typing/issues/258#issuecomment-237695460
https://github.com/gvanrossum
gvanrossumhttps://github.com/gvanrossum
on Aug 4, 2016https://github.com/python/typing/issues/258#issuecomment-237709811
https://github.com/gvanrossum
gvanrossumhttps://github.com/gvanrossum
on Aug 5, 2016https://github.com/python/typing/issues/258#issuecomment-237751250
https://github.com/ilevkivskyi
ilevkivskyihttps://github.com/ilevkivskyi
on Aug 5, 2016https://github.com/python/typing/issues/258#issuecomment-237912461
https://github.com/gvanrossum
gvanrossumhttps://github.com/gvanrossum
on Aug 6, 2016https://github.com/python/typing/issues/258#issuecomment-238029219
https://github.com/gvanrossum
gvanrossumhttps://github.com/gvanrossum
on Aug 8, 2016https://github.com/python/typing/issues/258#issuecomment-238324407
https://github.com/srkunze
srkunzehttps://github.com/srkunze
on Aug 8, 2016https://github.com/python/typing/issues/258#issuecomment-238372140
https://github.com/ilevkivskyi
ilevkivskyihttps://github.com/ilevkivskyi
on Aug 8, 2016https://github.com/python/typing/issues/258#issuecomment-238373119
@srkunzehttps://github.com/srkunze
https://github.com/srkunze
srkunzehttps://github.com/srkunze
on Aug 8, 2016https://github.com/python/typing/issues/258#issuecomment-238374176
https://github.com/ilevkivskyi
ilevkivskyihttps://github.com/ilevkivskyi
on Aug 8, 2016https://github.com/python/typing/issues/258#issuecomment-238376965
@srkunzehttps://github.com/srkunze
https://github.com/srkunze
srkunzehttps://github.com/srkunze
on Aug 8, 2016https://github.com/python/typing/issues/258#issuecomment-238377145
@ilevkivskyihttps://github.com/ilevkivskyi
https://github.com/elazarg
elazarghttps://github.com/elazarg
on Aug 8, 2016https://github.com/python/typing/issues/258#issuecomment-238377661
https://github.com/srkunze
srkunzehttps://github.com/srkunze
on Aug 8, 2016https://github.com/python/typing/issues/258#issuecomment-238378098
@ilevkivskyihttps://github.com/ilevkivskyi
https://github.com/gvanrossum
gvanrossumhttps://github.com/gvanrossum
on Sep 7, 2016https://github.com/python/typing/issues/258#issuecomment-245339975
@SylvainCorlayhttps://github.com/SylvainCorlay
@fperezhttps://github.com/fperez
@Carreauhttps://github.com/Carreau
https://github.com/SylvainCorlay
SylvainCorlayhttps://github.com/SylvainCorlay
on Sep 7, 2016https://github.com/python/typing/issues/258#issuecomment-245350007
@SylvainCorlayhttps://github.com/SylvainCorlay
@fperezhttps://github.com/fperez
@Carreauhttps://github.com/Carreau
@ellisonbghttps://github.com/ellisonbg
@minrkhttps://github.com/minrk
https://github.com/ilevkivskyi
ilevkivskyihttps://github.com/ilevkivskyi
on Sep 7, 2016https://github.com/python/typing/issues/258#issuecomment-245433451
@gvanrossumhttps://github.com/gvanrossum
https://github.com/NeilGirdhar
NeilGirdharhttps://github.com/NeilGirdhar
on Sep 7, 2016https://github.com/python/typing/issues/258#issuecomment-245437809
@ilevkivskyihttps://github.com/ilevkivskyi
https://github.com/ilevkivskyi
ilevkivskyihttps://github.com/ilevkivskyi
on Sep 7, 2016https://github.com/python/typing/issues/258#issuecomment-245439857
@NeilGirdharhttps://github.com/NeilGirdhar
https://github.com/gvanrossum
gvanrossumhttps://github.com/gvanrossum
on Sep 7, 2016https://github.com/python/typing/issues/258#issuecomment-245448546
https://github.com/vedgar
vedgarhttps://github.com/vedgar
on Sep 8, 2016https://github.com/python/typing/issues/258#issuecomment-245483101
https://github.com/gvanrossum
gvanrossumhttps://github.com/gvanrossum
on Sep 8, 2016https://github.com/python/typing/issues/258#issuecomment-245484369
https://github.com/vedgar
vedgarhttps://github.com/vedgar
on Sep 8, 2016https://github.com/python/typing/issues/258#issuecomment-245485379
https://github.com/gvanrossum
gvanrossumhttps://github.com/gvanrossum
on Sep 8, 2016https://github.com/python/typing/issues/258#issuecomment-245488533
https://github.com/vedgar
vedgarhttps://github.com/vedgar
on Sep 8, 2016https://github.com/python/typing/issues/258#issuecomment-245490786
https://github.com/gvanrossum
gvanrossumhttps://github.com/gvanrossum
on Sep 8, 2016https://github.com/python/typing/issues/258#issuecomment-245617514
https://github.com/gvanrossum
gvanrossumhttps://github.com/gvanrossum
on May 10, 2017https://github.com/python/typing/issues/258#issuecomment-300521738
https://github.com/ilevkivskyi
ilevkivskyihttps://github.com/ilevkivskyi
on May 10, 2017https://github.com/python/typing/issues/258#issuecomment-300609909
ilevkivskyihttps://github.com/ilevkivskyi
completedhttps://github.com/python/typing/issues?q=is%3Aissue%20state%3Aclosed%20archived%3Afalse%20reason%3Acompleted
on May 10, 2017https://github.com/python/typing/issues/258#event-1077182027
Sign up for freehttps://github.com/signup?return_to=https://github.com/python/typing/issues/258
Sign in to commenthttps://github.com/login?return_to=https://github.com/python/typing/issues/258
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.