{"id":13468238,"url":"https://github.com/asottile/pyupgrade","last_synced_at":"2025-05-13T15:06:18.757Z","repository":{"id":37484415,"uuid":"83462592","full_name":"asottile/pyupgrade","owner":"asottile","description":"A tool (and pre-commit hook) to automatically upgrade syntax for newer versions of the language.","archived":false,"fork":false,"pushed_at":"2025-03-31T21:00:16.000Z","size":1213,"stargazers_count":3756,"open_issues_count":21,"forks_count":191,"subscribers_count":35,"default_branch":"main","last_synced_at":"2025-05-05T22:41:59.399Z","etag":null,"topics":["linter","pre-commit","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/asottile.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"asottile"}},"created_at":"2017-02-28T17:50:31.000Z","updated_at":"2025-05-03T02:36:05.000Z","dependencies_parsed_at":"2024-01-12T20:50:03.939Z","dependency_job_id":"c6220d27-a6fd-4462-b0e2-ee19a7560e90","html_url":"https://github.com/asottile/pyupgrade","commit_stats":{"total_commits":749,"total_committers":37,"mean_commits":"20.243243243243242","dds":0.2750333778371161,"last_synced_commit":"ead7440b01d7912d7385c9e71c631742da0710e7"},"previous_names":[],"tags_count":174,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/asottile%2Fpyupgrade","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/asottile%2Fpyupgrade/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/asottile%2Fpyupgrade/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/asottile%2Fpyupgrade/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/asottile","download_url":"https://codeload.github.com/asottile/pyupgrade/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253969225,"owners_count":21992262,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["linter","pre-commit","python"],"created_at":"2024-07-31T15:01:07.465Z","updated_at":"2025-05-13T15:06:18.719Z","avatar_url":"https://github.com/asottile.png","language":"Python","readme":"[![build status](https://github.com/asottile/pyupgrade/actions/workflows/main.yml/badge.svg)](https://github.com/asottile/pyupgrade/actions/workflows/main.yml)\n[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/asottile/pyupgrade/main.svg)](https://results.pre-commit.ci/latest/github/asottile/pyupgrade/main)\n\npyupgrade\n=========\n\nA tool (and pre-commit hook) to automatically upgrade syntax for newer\nversions of the language.\n\n## Installation\n\n```bash\npip install pyupgrade\n```\n\n## As a pre-commit hook\n\nSee [pre-commit](https://github.com/pre-commit/pre-commit) for instructions\n\nSample `.pre-commit-config.yaml`:\n\n```yaml\n-   repo: https://github.com/asottile/pyupgrade\n    rev: v3.19.1\n    hooks:\n    -   id: pyupgrade\n```\n\n## Implemented features\n\n### Set literals\n\n```diff\n-set(())\n+set()\n-set([])\n+set()\n-set((1,))\n+{1}\n-set((1, 2))\n+{1, 2}\n-set([1, 2])\n+{1, 2}\n-set(x for x in y)\n+{x for x in y}\n-set([x for x in y])\n+{x for x in y}\n```\n\n### Dictionary comprehensions\n\n```diff\n-dict((a, b) for a, b in y)\n+{a: b for a, b in y}\n-dict([(a, b) for a, b in y])\n+{a: b for a, b in y}\n```\n\n### Replace unnecessary lambdas in `collections.defaultdict` calls\n\n```diff\n-defaultdict(lambda: [])\n+defaultdict(list)\n-defaultdict(lambda: list())\n+defaultdict(list)\n-defaultdict(lambda: {})\n+defaultdict(dict)\n-defaultdict(lambda: dict())\n+defaultdict(dict)\n-defaultdict(lambda: ())\n+defaultdict(tuple)\n-defaultdict(lambda: tuple())\n+defaultdict(tuple)\n-defaultdict(lambda: set())\n+defaultdict(set)\n-defaultdict(lambda: 0)\n+defaultdict(int)\n-defaultdict(lambda: 0.0)\n+defaultdict(float)\n-defaultdict(lambda: 0j)\n+defaultdict(complex)\n-defaultdict(lambda: '')\n+defaultdict(str)\n```\n\n### Format Specifiers\n\n```diff\n-'{0} {1}'.format(1, 2)\n+'{} {}'.format(1, 2)\n-'{0}' '{1}'.format(1, 2)\n+'{}' '{}'.format(1, 2)\n```\n\n### printf-style string formatting\n\nAvailability:\n- Unless `--keep-percent-format` is passed.\n\n```diff\n-'%s %s' % (a, b)\n+'{} {}'.format(a, b)\n-'%r %2f' % (a, b)\n+'{!r} {:2f}'.format(a, b)\n-'%(a)s %(b)s' % {'a': 1, 'b': 2}\n+'{a} {b}'.format(a=1, b=2)\n```\n\n### Unicode literals\n\n```diff\n-u'foo'\n+'foo'\n-u\"foo\"\n+'foo'\n-u'''foo'''\n+'''foo'''\n```\n\n### Invalid escape sequences\n\n```diff\n # strings with only invalid sequences become raw strings\n-'\\d'\n+r'\\d'\n # strings with mixed valid / invalid sequences get escaped\n-'\\n\\d'\n+'\\n\\\\d'\n-u'\\d'\n+r'\\d'\n # this fixes a syntax error in python3.3+\n-'\\N'\n+r'\\N'\n```\n\n### `is` / `is not` comparison to constant literals\n\nIn python3.8+, comparison to literals becomes a `SyntaxWarning` as the success\nof those comparisons is implementation specific (due to common object caching).\n\n```diff\n-x is 5\n+x == 5\n-x is not 5\n+x != 5\n-x is 'foo'\n+x == 'foo'\n```\n\n### `.encode()` to bytes literals\n\n```diff\n-'foo'.encode()\n+b'foo'\n-'foo'.encode('ascii')\n+b'foo'\n-'foo'.encode('utf-8')\n+b'foo'\n-u'foo'.encode()\n+b'foo'\n-'\\xa0'.encode('latin1')\n+b'\\xa0'\n```\n\n### extraneous parens in `print(...)`\n\nA fix for [python-modernize/python-modernize#178]\n\n```diff\n # ok: printing an empty tuple\n print(())\n # ok: printing a tuple\n print((1,))\n # ok: parenthesized generator argument\n sum((i for i in range(3)), [])\n # fixed:\n-print((\"foo\"))\n+print(\"foo\")\n```\n\n[python-modernize/python-modernize#178]: https://github.com/python-modernize/python-modernize/issues/178\n\n### constant fold `isinstance` / `issubclass` / `except`\n\n```diff\n-isinstance(x, (int, int))\n+isinstance(x, int)\n\n-issubclass(y, (str, str))\n+issubclass(y, str)\n\n try:\n     raises()\n-except (Error1, Error1, Error2):\n+except (Error1, Error2):\n     pass\n```\n\n### unittest deprecated aliases\n\nRewrites [deprecated unittest method aliases](https://docs.python.org/3/library/unittest.html#deprecated-aliases) to their non-deprecated forms.\n\n```diff\n from unittest import TestCase\n\n\n class MyTests(TestCase):\n     def test_something(self):\n-        self.failUnlessEqual(1, 1)\n+        self.assertEqual(1, 1)\n-        self.assertEquals(1, 1)\n+        self.assertEqual(1, 1)\n```\n\n### `super()` calls\n\n```diff\n class C(Base):\n     def f(self):\n-        super(C, self).f()\n+        super().f()\n```\n\n### \"new style\" classes\n\n#### rewrites class declaration\n\n```diff\n-class C(object): pass\n+class C: pass\n-class C(B, object): pass\n+class C(B): pass\n```\n\n#### removes `__metaclass__ = type` declaration\n\n```diff\n class C:\n-    __metaclass__ = type\n```\n\n### forced `str(\"native\")` literals\n\n```diff\n-str()\n+''\n-str(\"foo\")\n+\"foo\"\n```\n\n### `.encode(\"utf-8\")`\n\n```diff\n-\"foo\".encode(\"utf-8\")\n+\"foo\".encode()\n```\n\n### `# coding: ...` comment\n\nas of [PEP 3120], the default encoding for python source is UTF-8\n\n```diff\n-# coding: utf-8\n x = 1\n```\n\n[PEP 3120]: https://www.python.org/dev/peps/pep-3120/\n\n### `__future__` import removal\n\nAvailability:\n- by default removes `nested_scopes`, `generators`, `with_statement`,\n  `absolute_import`, `division`, `print_function`, `unicode_literals`\n- `--py37-plus` will also remove `generator_stop`\n\n```diff\n-from __future__ import with_statement\n```\n\n### Remove unnecessary py3-compat imports\n\n```diff\n-from io import open\n-from six.moves import map\n-from builtins import object  # python-future\n```\n\n### import replacements\n\nAvailability:\n- `--py36-plus` (and others) will replace imports\n\nsee also [reorder-python-imports](https://github.com/asottile/reorder_python_imports#removing--rewriting-obsolete-six-imports)\n\nsome examples:\n\n```diff\n-from collections import deque, Mapping\n+from collections import deque\n+from collections.abc import Mapping\n```\n\n```diff\n-from typing import Sequence\n+from collections.abc import Sequence\n```\n\n```diff\n-from typing_extensions import Concatenate\n+from typing import Concatenate\n```\n\n### rewrite `mock` imports\n\nAvailability:\n- [Unless `--keep-mock` is passed on the commandline](https://github.com/asottile/pyupgrade/issues/314).\n\n```diff\n-from mock import patch\n+from unittest.mock import patch\n```\n\n### `yield` =\u003e `yield from`\n\n```diff\n def f():\n-    for x in y:\n-        yield x\n+    yield from y\n-    for a, b in c:\n-        yield (a, b)\n+    yield from c\n```\n\n### Python2 and old Python3.x blocks\n\n```diff\n import sys\n-if sys.version_info \u003c (3,):  # also understands `six.PY2` (and `not`), `six.PY3` (and `not`)\n-    print('py2')\n-else:\n-    print('py3')\n+print('py3')\n```\n\nAvailability:\n- `--py36-plus` will remove Python \u003c= 3.5 only blocks\n- `--py37-plus` will remove Python \u003c= 3.6 only blocks\n- so on and so forth\n\n```diff\n # using --py36-plus for this example\n\n import sys\n-if sys.version_info \u003c (3, 6):\n-    print('py3.5')\n-else:\n-    print('py3.6+')\n+print('py3.6+')\n\n-if sys.version_info \u003c= (3, 5):\n-    print('py3.5')\n-else:\n-    print('py3.6+')\n+print('py3.6+')\n\n-if sys.version_info \u003e= (3, 6):\n-    print('py3.6+')\n-else:\n-    print('py3.5')\n+print('py3.6+')\n```\n\nNote that `if` blocks without an `else` will not be rewritten as it could introduce a syntax error.\n\n### remove `six` compatibility code\n\n```diff\n-six.text_type\n+str\n-six.binary_type\n+bytes\n-six.class_types\n+(type,)\n-six.string_types\n+(str,)\n-six.integer_types\n+(int,)\n-six.unichr\n+chr\n-six.iterbytes\n+iter\n-six.print_(...)\n+print(...)\n-six.exec_(c, g, l)\n+exec(c, g, l)\n-six.advance_iterator(it)\n+next(it)\n-six.next(it)\n+next(it)\n-six.callable(x)\n+callable(x)\n-six.moves.range(x)\n+range(x)\n-six.moves.xrange(x)\n+range(x)\n\n\n-from six import text_type\n-text_type\n+str\n\n-@six.python_2_unicode_compatible\n class C:\n     def __str__(self):\n         return u'C()'\n\n-class C(six.Iterator): pass\n+class C: pass\n\n-class C(six.with_metaclass(M, B)): pass\n+class C(B, metaclass=M): pass\n\n-@six.add_metaclass(M)\n-class C(B): pass\n+class C(B, metaclass=M): pass\n\n-isinstance(..., six.class_types)\n+isinstance(..., type)\n-issubclass(..., six.integer_types)\n+issubclass(..., int)\n-isinstance(..., six.string_types)\n+isinstance(..., str)\n\n-six.b('...')\n+b'...'\n-six.u('...')\n+'...'\n-six.byte2int(bs)\n+bs[0]\n-six.indexbytes(bs, i)\n+bs[i]\n-six.int2byte(i)\n+bytes((i,))\n-six.iteritems(dct)\n+dct.items()\n-six.iterkeys(dct)\n+dct.keys()\n-six.itervalues(dct)\n+dct.values()\n-next(six.iteritems(dct))\n+next(iter(dct.items()))\n-next(six.iterkeys(dct))\n+next(iter(dct.keys()))\n-next(six.itervalues(dct))\n+next(iter(dct.values()))\n-six.viewitems(dct)\n+dct.items()\n-six.viewkeys(dct)\n+dct.keys()\n-six.viewvalues(dct)\n+dct.values()\n-six.create_unbound_method(fn, cls)\n+fn\n-six.get_unbound_function(meth)\n+meth\n-six.get_method_function(meth)\n+meth.__func__\n-six.get_method_self(meth)\n+meth.__self__\n-six.get_function_closure(fn)\n+fn.__closure__\n-six.get_function_code(fn)\n+fn.__code__\n-six.get_function_defaults(fn)\n+fn.__defaults__\n-six.get_function_globals(fn)\n+fn.__globals__\n-six.raise_from(exc, exc_from)\n+raise exc from exc_from\n-six.reraise(tp, exc, tb)\n+raise exc.with_traceback(tb)\n-six.reraise(*sys.exc_info())\n+raise\n-six.assertCountEqual(self, a1, a2)\n+self.assertCountEqual(a1, a2)\n-six.assertRaisesRegex(self, e, r, fn)\n+self.assertRaisesRegex(e, r, fn)\n-six.assertRegex(self, s, r)\n+self.assertRegex(s, r)\n\n # note: only for *literals*\n-six.ensure_binary('...')\n+b'...'\n-six.ensure_str('...')\n+'...'\n-six.ensure_text('...')\n+'...'\n```\n\n### `open` alias\n\n```diff\n-with io.open('f.txt') as f:\n+with open('f.txt') as f:\n     ...\n```\n\n\n### redundant `open` modes\n\n```diff\n-open(\"foo\", \"U\")\n+open(\"foo\")\n-open(\"foo\", \"Ur\")\n+open(\"foo\")\n-open(\"foo\", \"Ub\")\n+open(\"foo\", \"rb\")\n-open(\"foo\", \"rUb\")\n+open(\"foo\", \"rb\")\n-open(\"foo\", \"r\")\n+open(\"foo\")\n-open(\"foo\", \"rt\")\n+open(\"foo\")\n-open(\"f\", \"r\", encoding=\"UTF-8\")\n+open(\"f\", encoding=\"UTF-8\")\n-open(\"f\", \"wt\")\n+open(\"f\", \"w\")\n```\n\n\n### `OSError` aliases\n\n```diff\n # also understands:\n # - IOError\n # - WindowsError\n # - mmap.error and uses of `from mmap import error`\n # - select.error and uses of `from select import error`\n # - socket.error and uses of `from socket import error`\n\n def throw():\n-    raise EnvironmentError('boom')\n+    raise OSError('boom')\n\n def catch():\n     try:\n         throw()\n-    except EnvironmentError:\n+    except OSError:\n         handle_error()\n```\n\n### `TimeoutError` aliases\n\nAvailability:\n- `--py310-plus` for `socket.timeout`\n- `--py311-plus` for `asyncio.TimeoutError`\n\n```diff\n\n def throw(a):\n     if a:\n-        raise asyncio.TimeoutError('boom')\n+        raise TimeoutError('boom')\n     else:\n-        raise socket.timeout('boom')\n+        raise TimeoutError('boom')\n\n def catch(a):\n     try:\n         throw(a)\n-    except (asyncio.TimeoutError, socket.timeout):\n+    except TimeoutError:\n         handle_error()\n```\n\n### `typing.Text` str alias\n\n```diff\n-def f(x: Text) -\u003e None:\n+def f(x: str) -\u003e None:\n     ...\n```\n\n\n### Unpacking list comprehensions\n\n```diff\n-foo, bar, baz = [fn(x) for x in items]\n+foo, bar, baz = (fn(x) for x in items)\n```\n\n\n### Rewrite `xml.etree.cElementTree` to `xml.etree.ElementTree`\n\n```diff\n-import xml.etree.cElementTree as ET\n+import xml.etree.ElementTree as ET\n-from xml.etree.cElementTree import XML\n+from xml.etree.ElementTree import XML\n```\n\n\n### Rewrite `type` of primitive\n\n```diff\n-type('')\n+str\n-type(b'')\n+bytes\n-type(0)\n+int\n-type(0.)\n+float\n```\n\n### `typing.NamedTuple` / `typing.TypedDict` py36+ syntax\n\nAvailability:\n- `--py36-plus` is passed on the commandline.\n\n```diff\n-NT = typing.NamedTuple('NT', [('a', int), ('b', Tuple[str, ...])])\n+class NT(typing.NamedTuple):\n+    a: int\n+    b: Tuple[str, ...]\n\n-D1 = typing.TypedDict('D1', a=int, b=str)\n+class D1(typing.TypedDict):\n+    a: int\n+    b: str\n\n-D2 = typing.TypedDict('D2', {'a': int, 'b': str})\n+class D2(typing.TypedDict):\n+    a: int\n+    b: str\n```\n\n### f-strings\n\nAvailability:\n- `--py36-plus` is passed on the commandline.\n\n```diff\n-'{foo} {bar}'.format(foo=foo, bar=bar)\n+f'{foo} {bar}'\n-'{} {}'.format(foo, bar)\n+f'{foo} {bar}'\n-'{} {}'.format(foo.bar, baz.womp)\n+f'{foo.bar} {baz.womp}'\n-'{} {}'.format(f(), g())\n+f'{f()} {g()}'\n-'{x}'.format(**locals())\n+f'{x}'\n```\n\n_note_: `pyupgrade` is intentionally timid and will not create an f-string\nif it would make the expression longer or if the substitution parameters are\nsufficiently complicated (as this can decrease readability).\n\n\n### `subprocess.run`: replace `universal_newlines` with `text`\n\nAvailability:\n- `--py37-plus` is passed on the commandline.\n\n```diff\n-output = subprocess.run(['foo'], universal_newlines=True)\n+output = subprocess.run(['foo'], text=True)\n```\n\n\n### `subprocess.run`: replace `stdout=subprocess.PIPE, stderr=subprocess.PIPE` with `capture_output=True`\n\nAvailability:\n- `--py37-plus` is passed on the commandline.\n\n```diff\n-output = subprocess.run(['foo'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n+output = subprocess.run(['foo'], capture_output=True)\n```\n\n\n### remove parentheses from `@functools.lru_cache()`\n\nAvailability:\n- `--py38-plus` is passed on the commandline.\n\n```diff\n import functools\n\n-@functools.lru_cache()\n+@functools.lru_cache\n def expensive():\n     ...\n```\n\n### shlex.join\n\nAvailability:\n- `--py38-plus` is passed on the commandline.\n\n```diff\n-' '.join(shlex.quote(arg) for arg in cmd)\n+shlex.join(cmd)\n```\n\n### replace `@functools.lru_cache(maxsize=None)` with shorthand\n\nAvailability:\n- `--py39-plus` is passed on the commandline.\n\n```diff\n import functools\n\n-@functools.lru_cache(maxsize=None)\n+@functools.cache\n def expensive():\n     ...\n```\n\n\n### pep 585 typing rewrites\n\nAvailability:\n- File imports `from __future__ import annotations`\n    - Unless `--keep-runtime-typing` is passed on the commandline.\n- `--py39-plus` is passed on the commandline.\n\n```diff\n-def f(x: List[str]) -\u003e None:\n+def f(x: list[str]) -\u003e None:\n     ...\n```\n\n\n### pep 604 typing rewrites\n\nAvailability:\n- File imports `from __future__ import annotations`\n    - Unless `--keep-runtime-typing` is passed on the commandline.\n- `--py310-plus` is passed on the commandline.\n\n```diff\n-def f() -\u003e Optional[str]:\n+def f() -\u003e str | None:\n     ...\n```\n\n```diff\n-def f() -\u003e Union[int, str]:\n+def f() -\u003e int | str:\n     ...\n```\n\n### pep 696 TypeVar defaults\n\nAvailability:\n- File imports `from __future__ import annotations`\n    - Unless `--keep-runtime-typing` is passed on the commandline.\n- `--py313-plus` is passed on the commandline.\n\n```diff\n-def f() -\u003e Generator[int, None, None]:\n+def f() -\u003e Generator[int]:\n     yield 1\n```\n\n```diff\n-async def f() -\u003e AsyncGenerator[int, None]:\n+async def f() -\u003e AsyncGenerator[int]:\n     yield 1\n```\n\n### remove quoted annotations\n\nAvailability:\n- File imports `from __future__ import annotations`\n\n```diff\n-def f(x: 'queue.Queue[int]') -\u003e C:\n+def f(x: queue.Queue[int]) -\u003e C:\n```\n\n\n### use `datetime.UTC` alias\n\nAvailability:\n- `--py311-plus` is passed on the commandline.\n\n```diff\n import datetime\n\n-datetime.timezone.utc\n+datetime.UTC\n```\n","funding_links":["https://github.com/sponsors/asottile"],"categories":["Python","By Environment","Containers \u0026 Language Extentions \u0026 Linting","Software Engineering","Other","Code Refactoring","Upgrading tools"],"sub_categories":["Python","For Python","Curated Python packages"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fasottile%2Fpyupgrade","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fasottile%2Fpyupgrade","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fasottile%2Fpyupgrade/lists"}