Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .cache/pip/http-v2/3/4/e/4/e/34e4ed9f6da78ec378e04be04de734c69a68c889dbef86cb0f5f498aAdded
- .cache/pip/http-v2/3/4/e/4/e/34e4ed9f6da78ec378e04be04de734c69a68c889dbef86cb0f5f498a.bodyAdded
- .cache/pip/http-v2/3/5/a/0/6/35a0615e0411edd59492c90e8f5cd0a1a0554d6f7d1dec5be2b30560Added
- .cache/pip/http-v2/3/5/a/0/6/35a0615e0411edd59492c90e8f5cd0a1a0554d6f7d1dec5be2b30560.bodyAdded+97
- .cache/pip/http-v2/3/7/c/5/1/37c518ffee828550acec5a0fd158a5f1d852928eea13df9d077b428bAdded
- .cache/pip/http-v2/3/7/c/5/1/37c518ffee828550acec5a0fd158a5f1d852928eea13df9d077b428b.bodyAdded
- .cache/pip/http-v2/3/8/6/0/e/3860e4de9ae53c79d2fd61419e9049df314ccc8b640782c02c6e2e2dAdded
- .cache/pip/http-v2/3/8/6/0/e/3860e4de9ae53c79d2fd61419e9049df314ccc8b640782c02c6e2e2d.bodyAdded
- .cache/pip/http-v2/3/8/9/2/7/389270eb64d5d655add63491064e7e833611004a96c2fb8b19caa5fbAdded
- .cache/pip/http-v2/3/8/9/2/7/389270eb64d5d655add63491064e7e833611004a96c2fb8b19caa5fb.bodyAdded+321
- .cache/pip/http-v2/3/8/c/c/8/38cc8209283ecb2d228ea8086bb74fbdc5d4872485c51a94fdb9c6cbAdded
- .cache/pip/http-v2/4/4/a/d/5/44ad51ab4fe732177892254938ca19df59a19add805fe17b3b22c658Added
- .cache/pip/http-v2/4/4/a/d/5/44ad51ab4fe732177892254938ca19df59a19add805fe17b3b22c658.bodyAdded+1595
- .cache/pip/http-v2/4/6/5/f/3/465f3fcecb7ed980c1b4d56b4f1ac8b2ae4685d32a696bbd51a25fb9Added
- .cache/pip/http-v2/4/6/5/f/3/465f3fcecb7ed980c1b4d56b4f1ac8b2ae4685d32a696bbd51a25fb9.bodyAdded+329
- .cache/pip/http-v2/4/a/5/b/6/4a5b6f0d76201de4cfd4884f5e95617a1848cf81c8357be4d12cbf6aAdded
- .cache/pip/http-v2/4/a/5/b/6/4a5b6f0d76201de4cfd4884f5e95617a1848cf81c8357be4d12cbf6a.bodyAdded+86
- .cache/pip/http-v2/4/d/c/8/d/4dc8d567db4bc55c0684404c85a6b4572f87a99306be24cab65fbfaeAdded
- .cache/pip/http-v2/4/d/c/8/d/4dc8d567db4bc55c0684404c85a6b4572f87a99306be24cab65fbfae.bodyAdded
- .cache/pip/http-v2/4/f/3/2/1/4f3214a3fad8d38cb17e7de04e5671458da4f4634932269127d53af7Added
- .cache/pip/http-v2/9/b/5/1/6/9b51619e20a708f99372afefd7dbe20a1b5e42ae213f02bf27267976Added
- .cache/pip/http-v2/c/3/a/e/f/c3aefa2552222433000010e47def822725a77e3cf762f96a15f09d26Added
- .cache/pip/http-v2/c/3/a/e/f/c3aefa2552222433000010e47def822725a77e3cf762f96a15f09d26.bodyAdded+907
- .cache/pip/http-v2/c/6/3/0/6/c6306d205b48faecb62eb823053e850df036f38e59b11523829f5c31Added
- .cache/pip/http-v2/c/6/3/0/6/c6306d205b48faecb62eb823053e850df036f38e59b11523829f5c31.bodyAdded
- .cache/pip/http-v2/c/8/4/4/6/c84464fe37be1d534151bcdb9cc17e882f3b79853f43ffdb6425f333Added
- .cache/pip/http-v2/c/8/4/4/6/c84464fe37be1d534151bcdb9cc17e882f3b79853f43ffdb6425f333.bodyAdded+1086
- .cache/pip/http-v2/c/c/c/b/4/cccb41730ba9dcdb4cb7127715ba43b53bfd809d6ff652fe215567a3Added
- .cache/pip/http-v2/c/c/c/b/4/cccb41730ba9dcdb4cb7127715ba43b53bfd809d6ff652fe215567a3.bodyAdded+300
- .cache/pip/http-v2/c/d/5/d/e/cd5de44b899cbe1869765c21b55cffc53c0c0ffa9d3c6f1fd40a42a2Added
- .cache/pip/http-v2/f/9/5/d/2/f95d294c2281f9705ab34177ee4732e524880c56ef894e620cf4cb95Added
- .cache/pip/http-v2/f/9/5/d/2/f95d294c2281f9705ab34177ee4732e524880c56ef894e620cf4cb95.bodyAdded
- .cache/pip/http-v2/f/c/6/8/7/fc687abc6120c7bc7cfd867fe3788604e9f8e9dcf17e51396d803e25Added
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock-3.29.0.dist-info/METADATAAdded+38
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock-3.29.0.dist-info/RECORDAdded+19
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock-3.29.0.dist-info/WHEELAdded+4
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock-3.29.0.dist-info/licenses/LICENSEAdded+21
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/__init__.pyAdded+93
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_api.pyAdded+582
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_async_read_write.pyAdded+207
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_error.pyAdded+30
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_read_write.pyAdded+364
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_soft.pyAdded+214
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_soft_rw/_async.pyAdded+213
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_soft_rw/_sync.pyAdded+847
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_unix.pyAdded+116
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_util.pyAdded+53
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_windows.pyAdded+111
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/asyncio.pyAdded+385
- .cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/py.typedAdded
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697Metadata-Version: 2.4Name: kiwisolverVersion: 1.5.0Summary: A fast implementation of the Cassowary constraint solverAuthor-email: The Nucleic Development Team <sccolbert@gmail.com>Maintainer-email: "Matthieu C. Dartiailh" <m.dartiailh@gmail.com>License: ========================= The Kiwi licensing terms ========================= Kiwi is licensed under the terms of the Modified BSD License (also known as New or Revised BSD), as follows: Copyright (c) 2013-2026, Nucleic Development Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Nucleic Development Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. About Kiwi ---------- Chris Colbert began the Kiwi project in December 2013 in an effort to create a blisteringly fast UI constraint solver. Chris is still the project lead. The Nucleic Development Team is the set of all contributors to the Nucleic project and its subprojects. The core team that coordinates development on GitHub can be found here: http://github.com/nucleic. The current team consists of: * Chris Colbert Our Copyright Policy -------------------- Nucleic uses a shared copyright model. Each contributor maintains copyright over their contributions to Nucleic. But, it is important to note that these contributions are typically only changes to the repositories. Thus, the Nucleic source code, in its entirety is not the copyright of any single person or institution. Instead, it is the collective copyright of the entire Nucleic Development Team. If individual contributors want to maintain a record of what changes/contributions they have specific copyright on, they should indicate their copyright in the commit message of the change, when they commit the change to one of the Nucleic repositories. With this in mind, the following banner should be used in any source code file to indicate the copyright and license terms: #------------------------------------------------------------------------------ # Copyright (c) 2013-2026, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. #------------------------------------------------------------------------------ Project-URL: homepage, https://github.com/nucleic/kiwiProject-URL: documentation, https://kiwisolver.readthedocs.io/en/latest/Project-URL: repository, https://github.com/nucleic/kiwiProject-URL: changelog, https://github.com/nucleic/kiwi/blob/main/releasenotes.rstClassifier: License :: OSI Approved :: BSD LicenseClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Programming Language :: Python :: Implementation :: GraalPyRequires-Python: >=3.10Description-Content-Type: text/x-rstLicense-File: LICENSEDynamic: license-file123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321Metadata-Version: 2.4Name: colorlogVersion: 6.10.1Summary: Add colours to the output of Python's logging module.Home-page: https://github.com/borntyping/python-colorlogAuthor: Sam ClementsAuthor-email: sam@borntyping.co.ukLicense: MIT LicenseClassifier: Development Status :: 5 - Production/StableClassifier: Environment :: ConsoleClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: MIT LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.6Classifier: Programming Language :: Python :: 3.7Classifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Topic :: TerminalsClassifier: Topic :: UtilitiesRequires-Python: >=3.6Description-Content-Type: text/markdownLicense-File: LICENSERequires-Dist: colorama; sys_platform == "win32"Provides-Extra: developmentRequires-Dist: black; extra == "development"Requires-Dist: flake8; extra == "development"Requires-Dist: mypy; extra == "development"Requires-Dist: pytest; extra == "development"Requires-Dist: types-colorama; extra == "development"Dynamic: authorDynamic: author-emailDynamic: classifierDynamic: descriptionDynamic: description-content-typeDynamic: home-pageDynamic: licenseDynamic: license-fileDynamic: provides-extraDynamic: requires-pythonDynamic: summary
# Log formatting with colors!
[](https://pypi.org/project/colorlog/)[](https://pypi.org/project/colorlog/)
Add colours to the output of Python's `logging` module.
* [Source on GitHub](https://github.com/borntyping/python-colorlog)* [Packages on PyPI](https://pypi.org/pypi/colorlog/)
## Status
colorlog currently requires Python 3.6 or higher. Older versions (below 5.x.x) support Python 2.6 and above.
* colorlog 6.x requires Python 3.6 or higher.* colorlog 5.x is an interim version that will warn Python 2 users to downgrade.* colorlog 4.x is the final version supporting Python 2.
[colorama] is included as a required dependency and initialised when using colorlog on Windows.
This library is over a decade old and supported a wide set of Python versionsfor most of its life, which has made it a difficult library to add new featuresto. colorlog 6 may break backwards compatibility so that newer featurescan be added more easily, but may still not accept all changes or featurerequests. colorlog 4 might accept essential bugfixes but should not beconsidered actively maintained and will not accept any major changes or newfeatures.
## Installation
Install from PyPI with:
```bashpip install colorlog```
Several Linux distributions provide official packages ([Debian], [Arch], [Fedora], [Gentoo], [OpenSuse] and [Ubuntu]), and others have user provided packages([BSD ports], [Conda]).
## Usage
```pythonimport colorlog
handler = colorlog.StreamHandler()handler.setFormatter(colorlog.ColoredFormatter( '%(log_color)s%(levelname)s:%(name)s:%(message)s'))
logger = colorlog.getLogger('example')logger.addHandler(handler)```
The `ColoredFormatter` class takes several arguments:
- `format`: The format string used to output the message (required).- `datefmt`: An optional date format passed to the base class. See [`logging.Formatter`][Formatter].- `reset`: Implicitly adds a color reset code to the message output, unless the output already ends with one. Defaults to `True`.- `log_colors`: A mapping of record level names to color names. The defaults can be found in `colorlog.default_log_colors`, or the below example.- `secondary_log_colors`: A mapping of names to `log_colors` style mappings, defining additional colors that can be used in format strings. See below for an example.- `style`: Available on Python 3.2 and above. See [`logging.Formatter`][Formatter].
Color escape codes can be selected based on the log records level, by addingparameters to the format string:
- `log_color`: Return the color associated with the records level.- `<name>_log_color`: Return another color based on the records level if the formatter has secondary colors configured (see `secondary_log_colors` below).
Multiple escape codes can be used at once by joining them with commas whenconfiguring the color for a log level (but can't be used directly in the formatstring). For example, `black,bg_white` would use the escape codes for blacktext on a white background.
The following escape codes are made available for use in the format string:
- `{color}`, `fg_{color}`, `bg_{color}`: Foreground and background colors.- `bold`, `bold_{color}`, `fg_bold_{color}`, `bg_bold_{color}`: Bold/bright colors.- `thin`, `thin_{color}`, `fg_thin_{color}`: Thin colors (terminal dependent).- `reset`: Clear all formatting (both foreground and background colors).
The available color names are:
- `black`- `red`- `green`- `yellow`- `blue`,- `purple`- `cyan`- `white`
You can also use "bright" colors. These aren't standard ANSI codes, andsupport for these varies wildly across different terminals.
- `light_black`- `light_red`- `light_green`- `light_yellow`- `light_blue`- `light_purple`- `light_cyan`- `light_white`
## Examples

The following code creates a `ColoredFormatter` for use in a logging setup,using the default values for each argument.
```pythonfrom colorlog import ColoredFormatter
formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%')```
### Using `secondary_log_colors`
Secondary log colors are a way to have more than one color that is selectedbased on the log level. Each key in `secondary_log_colors` adds an attributethat can be used in format strings (`message` becomes `message_log_color`), andhas a corresponding value that is identical in format to the `log_colors`argument.
The following example highlights the level name using the default log colors,and highlights the message in red for `error` and `critical` level log messages.
```pythonfrom colorlog import ColoredFormatter
formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s", secondary_log_colors={ 'message': { 'ERROR': 'red', 'CRITICAL': 'red' } })```
### With [`dictConfig`][dictConfig]
```pythonlogging.config.dictConfig({ 'formatters': { 'colored': { '()': 'colorlog.ColoredFormatter', 'format': "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s" } }})```
A full example dictionary can be found in `tests/test_colorlog.py`.
### With [`fileConfig`][fileConfig]
```ini...
[formatters]keys=color
[formatter_color]class=colorlog.ColoredFormatterformat=%(log_color)s%(levelname)-8s%(reset)s %(bg_blue)s[%(name)s]%(reset)s %(message)s from fileConfigdatefmt=%m-%d %H:%M:%S```
An instance of ColoredFormatter created with those arguments will then be usedby any handlers that are configured to use the `color` formatter.
A full example configuration can be found in `tests/test_config.ini`.
### With custom log levels
ColoredFormatter will work with custom log levels added with[`logging.addLevelName`][addLevelName]:
```pythonimport logging, colorlogTRACE = 5logging.addLevelName(TRACE, 'TRACE')formatter = colorlog.ColoredFormatter(log_colors={'TRACE': 'yellow'})handler = logging.StreamHandler()handler.setFormatter(formatter)logger = logging.getLogger('example')logger.addHandler(handler)logger.setLevel('TRACE')logger.log(TRACE, 'a message using a custom level')```
## Tests
Tests similar to the above examples are found in `tests/test_colorlog.py`.
## Status
colorlog is in maintenance mode. I try and ensure bugfixes are published,but compatibility a wide set of Python versions makes this a difficultcodebase to add features to. Any changes that might break backwardscompatibility for existing users will not be considered.
## Alternatives
There are some more modern libraries for improving Python logging you mayfind useful.
- [structlog]- [jsonlog]
## Projects using colorlog
GitHub provides [a list of projects that depend on colorlog][dependents].
Some early adopters included [Errbot], [Pythran], and [zenlog].
## Licence
Copyright (c) 2012-2025 Sam Clements <sam@borntyping.co.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy ofthis software and associated documentation files (the "Software"), to deal inthe Software without restriction, including without limitation the rights touse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ofthe Software, and to permit persons to whom the Software is furnished to do so,subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESSFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS ORCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHERIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[dictConfig]: http://docs.python.org/3/library/logging.config.html#logging.config.dictConfig[fileConfig]: http://docs.python.org/3/library/logging.config.html#logging.config.fileConfig[addLevelName]: https://docs.python.org/3/library/logging.html#logging.addLevelName[Formatter]: http://docs.python.org/3/library/logging.html#logging.Formatter[tox]: http://tox.readthedocs.org/[Arch]: https://archlinux.org/packages/extra/any/python-colorlog/[BSD ports]: https://www.freshports.org/devel/py-colorlog/[colorama]: https://pypi.python.org/pypi/colorama[Conda]: https://anaconda.org/conda-forge/colorlog[Debian]: [https://packages.debian.org/buster/python3-colorlog](https://packages.debian.org/buster/python3-colorlog)[Errbot]: http://errbot.io/[Fedora]: https://src.fedoraproject.org/rpms/python-colorlog[Gentoo]: https://packages.gentoo.org/packages/dev-python/colorlog[OpenSuse]: http://rpm.pbone.net/index.php3?stat=3&search=python-colorlog&srodzaj=3[Pythran]: https://github.com/serge-sans-paille/pythran[Ubuntu]: https://launchpad.net/python-colorlog[zenlog]: https://github.com/ManufacturaInd/python-zenlog[structlog]: https://www.structlog.org/en/stable/[jsonlog]: https://github.com/borntyping/jsonlog[dependents]: https://github.com/borntyping/python-colorlog/network/dependents?package_id=UGFja2FnZS01MDk3NDcyMQ%3D%3D12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595Metadata-Version: 2.4Name: tqdmVersion: 4.67.3Summary: Fast, Extensible Progress MeterMaintainer-email: tqdm developers <devs@tqdm.ml>License: MPL-2.0 AND MITProject-URL: homepage, https://tqdm.github.ioProject-URL: repository, https://github.com/tqdm/tqdmProject-URL: changelog, https://tqdm.github.io/releasesProject-URL: wiki, https://github.com/tqdm/tqdm/wikiKeywords: progressbar,progressmeter,progress,bar,meter,rate,eta,console,terminal,timeClassifier: Development Status :: 5 - Production/StableClassifier: Environment :: ConsoleClassifier: Environment :: MacOS XClassifier: Environment :: Other EnvironmentClassifier: Environment :: Win32 (MS Windows)Classifier: Environment :: X11 ApplicationsClassifier: Framework :: IPythonClassifier: Framework :: JupyterClassifier: Intended Audience :: DevelopersClassifier: Intended Audience :: EducationClassifier: Intended Audience :: End Users/DesktopClassifier: Intended Audience :: Other AudienceClassifier: Intended Audience :: System AdministratorsClassifier: Operating System :: MacOSClassifier: Operating System :: MacOS :: MacOS XClassifier: Operating System :: MicrosoftClassifier: Operating System :: Microsoft :: MS-DOSClassifier: Operating System :: Microsoft :: WindowsClassifier: Operating System :: POSIXClassifier: Operating System :: POSIX :: BSDClassifier: Operating System :: POSIX :: BSD :: FreeBSDClassifier: Operating System :: POSIX :: LinuxClassifier: Operating System :: POSIX :: SunOS/SolarisClassifier: Operating System :: UnixClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.7Classifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: ImplementationClassifier: Programming Language :: Python :: Implementation :: IronPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Programming Language :: Unix ShellClassifier: Topic :: Desktop EnvironmentClassifier: Topic :: Education :: Computer Aided Instruction (CAI)Classifier: Topic :: Education :: TestingClassifier: Topic :: Office/BusinessClassifier: Topic :: Other/Nonlisted TopicClassifier: Topic :: Software Development :: Build ToolsClassifier: Topic :: Software Development :: LibrariesClassifier: Topic :: Software Development :: Libraries :: Python ModulesClassifier: Topic :: Software Development :: Pre-processorsClassifier: Topic :: Software Development :: User InterfacesClassifier: Topic :: System :: Installation/SetupClassifier: Topic :: System :: LoggingClassifier: Topic :: System :: MonitoringClassifier: Topic :: System :: ShellsClassifier: Topic :: TerminalsClassifier: Topic :: UtilitiesRequires-Python: >=3.7Description-Content-Type: text/x-rstLicense-File: LICENCERequires-Dist: colorama; platform_system == "Windows"Requires-Dist: importlib_metadata; python_version < "3.8"Provides-Extra: devRequires-Dist: pytest>=6; extra == "dev"Requires-Dist: pytest-cov; extra == "dev"Requires-Dist: pytest-timeout; extra == "dev"Requires-Dist: pytest-asyncio>=0.24; extra == "dev"Requires-Dist: nbval; extra == "dev"Provides-Extra: discordRequires-Dist: requests; extra == "discord"Provides-Extra: slackRequires-Dist: slack-sdk; extra == "slack"Provides-Extra: telegramRequires-Dist: requests; extra == "telegram"Provides-Extra: notebookRequires-Dist: ipywidgets>=6; extra == "notebook"Dynamic: license-file
|Logo|
tqdm====
|Py-Versions| |Versions| |Conda-Forge-Status| |Docker| |Snapcraft|
|Build-Status| |Coverage-Status| |Branch-Coverage-Status| |Codacy-Grade| |Libraries-Rank| |PyPI-Downloads|
|LICENCE| |OpenHub-Status| |binder-demo| |awesome-python|
``tqdm`` derives from the Arabic word *taqaddum* (تقدّم) which can mean "progress,"and is an abbreviation for "I love you so much" in Spanish (*te quiero demasiado*).
Instantly make your loops show a smart progress meter - just wrap anyiterable with ``tqdm(iterable)``, and you're done!
.. code:: python
from tqdm import tqdm for i in tqdm(range(10000)): ...
``76%|████████████████████████ | 7568/10000 [00:33<00:10, 229.00it/s]``
``trange(N)`` can be also used as a convenient shortcut for``tqdm(range(N))``.
|Screenshot| |Video| |Slides| |Merch|
It can also be executed as a module with pipes:
.. code:: sh
$ seq 9999999 | tqdm --bytes | wc -l 75.2MB [00:00, 217MB/s] 9999999
$ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \ > backup.tgz 32%|██████████▍ | 8.89G/27.9G [00:42<01:31, 223MB/s]
Overhead is low -- about 60ns per iteration (80ns with ``tqdm.gui``), and isunit tested against performance regression.By comparison, the well-established`ProgressBar <https://github.com/niltonvolpato/python-progressbar>`__ hasan 800ns/iter overhead.
In addition to its low overhead, ``tqdm`` uses smart algorithms to predictthe remaining time and to skip unnecessary iteration displays, which allowsfor a negligible overhead in most cases.
``tqdm`` works on any platform(Linux, Windows, Mac, FreeBSD, NetBSD, Solaris/SunOS),in any console or in a GUI, and is also friendly with IPython/Jupyter notebooks.
``tqdm`` does not require any dependencies (not even ``curses``!), justPython and an environment supporting ``carriage return \r`` and``line feed \n`` control characters.
------------------------------------------
.. contents:: Table of contents :backlinks: top :local:
Installation------------
Latest PyPI stable release~~~~~~~~~~~~~~~~~~~~~~~~~~
|Versions| |PyPI-Downloads| |Libraries-Dependents|
.. code:: sh
pip install tqdm
Latest development release on GitHub~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|GitHub-Status| |GitHub-Stars| |GitHub-Commits| |GitHub-Forks| |GitHub-Updated|
Pull and install pre-release ``devel`` branch:
.. code:: sh
pip install "git+https://github.com/tqdm/tqdm.git@devel#egg=tqdm"
Latest Conda release~~~~~~~~~~~~~~~~~~~~
|Conda-Forge-Status|
.. code:: sh
conda install -c conda-forge tqdm
Latest Snapcraft release~~~~~~~~~~~~~~~~~~~~~~~~
|Snapcraft|
There are 3 channels to choose from:
.. code:: sh
snap install tqdm # implies --stable, i.e. latest tagged release snap install tqdm --candidate # master branch snap install tqdm --edge # devel branch
Note that ``snap`` binaries are purely for CLI use (not ``import``-able), andautomatically set up ``bash`` tab-completion.
Latest Docker release~~~~~~~~~~~~~~~~~~~~~
|Docker|
.. code:: sh
docker pull tqdm/tqdm docker run -i --rm tqdm/tqdm --help
Other~~~~~
There are other (unofficial) places where ``tqdm`` may be downloaded, particularly for CLI use:
|Repology|
.. |Repology| image:: https://repology.org/badge/tiny-repos/python:tqdm.svg :target: https://repology.org/project/python:tqdm/versions
Changelog---------
The list of all changes is available either on GitHub's Releases:|GitHub-Status|, on the`wiki <https://github.com/tqdm/tqdm/wiki/Releases>`__, or on the`website <https://tqdm.github.io/releases>`__.
Usage-----
``tqdm`` is very versatile and can be used in a number of ways.The three main ones are given below.
Iterable-based~~~~~~~~~~~~~~
Wrap ``tqdm()`` around any iterable:
.. code:: python
from tqdm import tqdm from time import sleep
text = "" for char in tqdm(["a", "b", "c", "d"]): sleep(0.25) text = text + char
``trange(i)`` is a special optimised instance of ``tqdm(range(i))``:
.. code:: python
from tqdm import trange
for i in trange(100): sleep(0.01)
Instantiation outside of the loop allows for manual control over ``tqdm()``:
.. code:: python
pbar = tqdm(["a", "b", "c", "d"]) for char in pbar: sleep(0.25) pbar.set_description("Processing %s" % char)
Manual~~~~~~
Manual control of ``tqdm()`` updates using a ``with`` statement:
.. code:: python
with tqdm(total=100) as pbar: for i in range(10): sleep(0.1) pbar.update(10)
If the optional variable ``total`` (or an iterable with ``len()``) isprovided, predictive stats are displayed.
``with`` is also optional (you can just assign ``tqdm()`` to a variable,but in this case don't forget to ``del`` or ``close()`` at the end:
.. code:: python
pbar = tqdm(total=100) for i in range(10): sleep(0.1) pbar.update(10) pbar.close()
Module~~~~~~
Perhaps the most wonderful use of ``tqdm`` is in a script or on the commandline. Simply inserting ``tqdm`` (or ``python -m tqdm``) between pipes will passthrough all ``stdin`` to ``stdout`` while printing progress to ``stderr``.
The example below demonstrate counting the number of lines in all Python filesin the current directory, with timing information included.
.. code:: sh
$ time find . -name '*.py' -type f -exec cat \{} \; | wc -l 857365
real 0m3.458s user 0m0.274s sys 0m3.325s
$ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l 857366it [00:03, 246471.31it/s] 857365
real 0m3.585s user 0m0.862s sys 0m3.358s
Note that the usual arguments for ``tqdm`` can also be specified.
.. code:: sh
$ find . -name '*.py' -type f -exec cat \{} \; | tqdm --unit loc --unit_scale --total 857366 >> /dev/null 100%|█████████████████████████████████| 857K/857K [00:04<00:00, 246Kloc/s]
Backing up a large directory?
.. code:: sh
$ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \ > backup.tgz 44%|██████████████▊ | 153M/352M [00:14<00:18, 11.0MB/s]
This can be beautified further:
.. code:: sh
$ BYTES=$(du -sb docs/ | cut -f1) $ tar -cf - docs/ \ | tqdm --bytes --total "$BYTES" --desc Processing | gzip \ | tqdm --bytes --total "$BYTES" --desc Compressed --position 1 \ > ~/backup.tgz Processing: 100%|██████████████████████| 352M/352M [00:14<00:00, 30.2MB/s] Compressed: 42%|█████████▎ | 148M/352M [00:14<00:19, 10.9MB/s]
Or done on a file level using 7-zip:
.. code:: sh
$ 7z a -bd -r backup.7z docs/ | grep Compressing \ | tqdm --total $(find docs/ -type f | wc -l) --unit files \ | grep -v Compressing 100%|██████████████████████████▉| 15327/15327 [01:00<00:00, 712.96files/s]
Pre-existing CLI programs already outputting basic progress information willbenefit from ``tqdm``'s ``--update`` and ``--update_to`` flags:
.. code:: sh
$ seq 3 0.1 5 | tqdm --total 5 --update_to --null 100%|████████████████████████████████████| 5.0/5 [00:00<00:00, 9673.21it/s] $ seq 10 | tqdm --update --null # 1 + 2 + ... + 10 = 55 iterations 55it [00:00, 90006.52it/s]
FAQ and Known Issues--------------------
|GitHub-Issues|
The most common issues relate to excessive output on multiple lines, insteadof a neat one-line progress bar.
- Consoles in general: require support for carriage return (``CR``, ``\r``).
* Some cloud logging consoles which don't support ``\r`` properly (`cloudwatch <https://github.com/tqdm/tqdm/issues/966>`__, `K8s <https://github.com/tqdm/tqdm/issues/1319>`__) may benefit from ``export TQDM_POSITION=-1``.
- Nested progress bars:
* Consoles in general: require support for moving cursors up to the previous line. For example, `IDLE <https://github.com/tqdm/tqdm/issues/191#issuecomment-230168030>`__, `ConEmu <https://github.com/tqdm/tqdm/issues/254>`__ and `PyCharm <https://github.com/tqdm/tqdm/issues/203>`__ (also `here <https://github.com/tqdm/tqdm/issues/208>`__, `here <https://github.com/tqdm/tqdm/issues/307>`__, and `here <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__) lack full support. * Windows: additionally may require the Python module ``colorama`` to ensure nested bars stay within their respective lines.
- Unicode:
* Environments which report that they support unicode will have solid smooth progressbars. The fallback is an ``ascii``-only bar. * Windows consoles often only partially support unicode and thus `often require explicit ascii=True <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__ (also `here <https://github.com/tqdm/tqdm/issues/499>`__). This is due to either normal-width unicode characters being incorrectly displayed as "wide", or some unicode characters not rendering.
- Wrapping generators:
* Generator wrapper functions tend to hide the length of iterables. ``tqdm`` does not. * Replace ``tqdm(enumerate(...))`` with ``enumerate(tqdm(...))`` or ``tqdm(enumerate(x), total=len(x), ...)``. The same applies to ``numpy.ndenumerate``. * Replace ``tqdm(zip(a, b))`` with ``zip(tqdm(a), b)`` or even ``zip(tqdm(a), tqdm(b))``. * The same applies to ``itertools``. * Some useful convenience functions can be found under ``tqdm.contrib``.
- `No intermediate output in docker-compose <https://github.com/tqdm/tqdm/issues/771>`__: use ``docker-compose run`` instead of ``docker-compose up`` and ``tty: true``.
- Overriding defaults via environment variables: e.g. in CI/cloud jobs, ``export TQDM_MININTERVAL=5`` to avoid log spam. This override logic is handled by the ``tqdm.utils.envwrap`` decorator (useful independent of ``tqdm``).
If you come across any other difficulties, browse and file |GitHub-Issues|.
Documentation-------------
|Py-Versions| |README-Hits| (Since 19 May 2016)
.. code:: python
class tqdm(): """ Decorate an iterable object, returning an iterator which acts exactly like the original iterable, but prints a dynamically updating progressbar every time a value is requested. """
@envwrap("TQDM_") # override defaults via env vars def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None, ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None, ascii=None, disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0, position=None, postfix=None, unit_divisor=1000, write_bytes=False, lock_args=None, nrows=None, colour=None, delay=0):
Parameters~~~~~~~~~~
* iterable : iterable, optional Iterable to decorate with a progressbar. Leave blank to manually manage the updates.* desc : str, optional Prefix for the progressbar.* total : int or float, optional The number of expected iterations. If unspecified, len(iterable) is used if possible. If float("inf") or as a last resort, only basic progress statistics are displayed (no ETA, no progressbar). If ``gui`` is True and this parameter needs subsequent updating, specify an initial arbitrary large positive number, e.g. 9e9.* leave : bool, optional If [default: True], keeps all traces of the progressbar upon termination of iteration. If ``None``, will leave only if ``position`` is ``0``.* file : ``io.TextIOWrapper`` or ``io.StringIO``, optional Specifies where to output the progress messages (default: sys.stderr). Uses ``file.write(str)`` and ``file.flush()`` methods. For encoding, see ``write_bytes``.* ncols : int, optional The width of the entire output message. If specified, dynamically resizes the progressbar to stay within this bound. If unspecified, attempts to use environment width. The fallback is a meter width of 10 and no limit for the counter and statistics. If 0, will not print any meter (only stats).* mininterval : float, optional Minimum progress display update interval [default: 0.1] seconds.* maxinterval : float, optional Maximum progress display update interval [default: 10] seconds. Automatically adjusts ``miniters`` to correspond to ``mininterval`` after long display update lag. Only works if ``dynamic_miniters`` or monitor thread is enabled.* miniters : int or float, optional Minimum progress display update interval, in iterations. If 0 and ``dynamic_miniters``, will automatically adjust to equal ``mininterval`` (more CPU efficient, good for tight loops). If > 0, will skip display of specified number of iterations. Tweak this and ``mininterval`` to get very efficient loops. If your progress is erratic with both fast and slow iterations (network, skipping items, etc) you should set miniters=1.* ascii : bool or str, optional If unspecified or False, use unicode (smooth blocks) to fill the meter. The fallback is to use ASCII characters " 123456789#".* disable : bool, optional Whether to disable the entire progressbar wrapper [default: False]. If set to None, disable on non-TTY.* unit : str, optional String that will be used to define the unit of each iteration [default: it].* unit_scale : bool or int or float, optional If 1 or True, the number of iterations will be reduced/scaled automatically and a metric prefix following the International System of Units standard will be added (kilo, mega, etc.) [default: False]. If any other non-zero number, will scale ``total`` and ``n``.* dynamic_ncols : bool, optional If set, constantly alters ``ncols`` and ``nrows`` to the environment (allowing for window resizes) [default: False].* smoothing : float, optional Exponential moving average smoothing factor for speed estimates (ignored in GUI mode). Ranges from 0 (average speed) to 1 (current/instantaneous speed) [default: 0.3].* bar_format : str, optional Specify a custom bar string formatting. May impact performance. [default: '{l_bar}{bar}{r_bar}'], where l_bar='{desc}: {percentage:3.0f}%|' and r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ' '{rate_fmt}{postfix}]' Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta. Note that a trailing ": " is automatically removed after {desc} if the latter is empty.* initial : int or float, optional The initial counter value. Useful when restarting a progress bar [default: 0]. If using float, consider specifying ``{n:.3f}`` or similar in ``bar_format``, or specifying ``unit_scale``.* position : int, optional Specify the line offset to print this bar (starting from 0) Automatic if unspecified. Useful to manage multiple bars at once (eg, from threads).* postfix : dict or ``*``, optional Specify additional stats to display at the end of the bar. Calls ``set_postfix(**postfix)`` if possible (dict).* unit_divisor : float, optional [default: 1000], ignored unless ``unit_scale`` is True.* write_bytes : bool, optional Whether to write bytes. If (default: False) will write unicode.* lock_args : tuple, optional Passed to ``refresh`` for intermediate output (initialisation, iterating, and updating).* nrows : int, optional The screen height. If specified, hides nested bars outside this bound. If unspecified, attempts to use environment height. The fallback is 20.* colour : str, optional Bar colour (e.g. 'green', '#00ff00').* delay : float, optional Don't display until [default: 0] seconds have elapsed.
Extra CLI Options~~~~~~~~~~~~~~~~~
* delim : chr, optional Delimiting character [default: '\n']. Use '\0' for null. N.B.: on Windows systems, Python converts '\n' to '\r\n'.* buf_size : int, optional String buffer size in bytes [default: 256] used when ``delim`` is specified.* bytes : bool, optional If true, will count bytes, ignore ``delim``, and default ``unit_scale`` to True, ``unit_divisor`` to 1024, and ``unit`` to 'B'.* tee : bool, optional If true, passes ``stdin`` to both ``stderr`` and ``stdout``.* update : bool, optional If true, will treat input as newly elapsed iterations, i.e. numbers to pass to ``update()``. Note that this is slow (~2e5 it/s) since every input must be decoded as a number.* update_to : bool, optional If true, will treat input as total elapsed iterations, i.e. numbers to assign to ``self.n``. Note that this is slow (~2e5 it/s) since every input must be decoded as a number.* null : bool, optional If true, will discard input (no stdout).* manpath : str, optional Directory in which to install tqdm man pages.* comppath : str, optional Directory in which to place tqdm completion.* log : str, optional CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET.
Returns~~~~~~~
* out : decorated iterator.
.. code:: python
class tqdm(): def update(self, n=1): """ Manually update the progress bar, useful for streams such as reading files. E.g.: >>> t = tqdm(total=filesize) # Initialise >>> for current_buffer in stream: ... ... ... t.update(len(current_buffer)) >>> t.close() The last line is highly recommended, but possibly not necessary if ``t.update()`` will be called in such a way that ``filesize`` will be exactly reached and printed.
Parameters ---------- n : int or float, optional Increment to add to the internal counter of iterations [default: 1]. If using float, consider specifying ``{n:.3f}`` or similar in ``bar_format``, or specifying ``unit_scale``.
Returns ------- out : bool or None True if a ``display()`` was triggered. """
def close(self): """Cleanup and (if leave=False) close the progressbar."""
def clear(self, nomove=False): """Clear current bar display."""
def refresh(self): """ Force refresh the display of this bar.
Parameters ---------- nolock : bool, optional If ``True``, does not lock. If [default: ``False``]: calls ``acquire()`` on internal lock. lock_args : tuple, optional Passed to internal lock's ``acquire()``. If specified, will only ``display()`` if ``acquire()`` returns ``True``. """
def unpause(self): """Restart tqdm timer from last print time."""
def reset(self, total=None): """ Resets to 0 iterations for repeated use.
Consider combining with ``leave=True``.
Parameters ---------- total : int or float, optional. Total to use for the new bar. """
def set_description(self, desc=None, refresh=True): """ Set/modify description of the progress bar.
Parameters ---------- desc : str, optional refresh : bool, optional Forces refresh [default: True]. """
def set_postfix(self, ordered_dict=None, refresh=True, **tqdm_kwargs): """ Set/modify postfix (additional stats) with automatic formatting based on datatype.
Parameters ---------- ordered_dict : dict or OrderedDict, optional refresh : bool, optional Forces refresh [default: True]. kwargs : dict, optional """
@classmethod def write(cls, s, file=sys.stdout, end="\n"): """Print a message via tqdm (without overlap with bars)."""
@property def format_dict(self): """Public API for read-only member access."""
def display(self, msg=None, pos=None): """ Use ``self.sp`` to display ``msg`` in the specified ``pos``.
Consider overloading this function when inheriting to use e.g.: ``self.some_frontend(**self.format_dict)`` instead of ``self.sp``.
Parameters ---------- msg : str, optional. What to display (default: ``repr(self)``). pos : int, optional. Position to ``moveto`` (default: ``abs(self.pos)``). """
@classmethod @contextmanager def wrapattr(cls, stream, method, total=None, bytes=True, **tqdm_kwargs): """ stream : file-like object. method : str, "read" or "write". The result of ``read()`` and the first argument of ``write()`` should have a ``len()``.
>>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj: ... while True: ... chunk = fobj.read(chunk_size) ... if not chunk: ... break """
@classmethod def pandas(cls, *targs, **tqdm_kwargs): """Registers the current `tqdm` class with `pandas`."""
def trange(*args, **tqdm_kwargs): """Shortcut for `tqdm(range(*args), **tqdm_kwargs)`."""
Convenience Functions~~~~~~~~~~~~~~~~~~~~~
.. code:: python
def tqdm.contrib.tenumerate(iterable, start=0, total=None, tqdm_class=tqdm.auto.tqdm, **tqdm_kwargs): """Equivalent of `numpy.ndenumerate` or builtin `enumerate`."""
def tqdm.contrib.tzip(iter1, *iter2plus, **tqdm_kwargs): """Equivalent of builtin `zip`."""
def tqdm.contrib.tmap(function, *sequences, **tqdm_kwargs): """Equivalent of builtin `map`."""
Submodules~~~~~~~~~~
.. code:: python
class tqdm.notebook.tqdm(tqdm.tqdm): """IPython/Jupyter Notebook widget."""
class tqdm.auto.tqdm(tqdm.tqdm): """Automatically chooses beween `tqdm.notebook` and `tqdm.tqdm`."""
class tqdm.asyncio.tqdm(tqdm.tqdm): """Asynchronous version.""" @classmethod def as_completed(cls, fs, *, loop=None, timeout=None, total=None, **tqdm_kwargs): """Wrapper for `asyncio.as_completed`."""
class tqdm.gui.tqdm(tqdm.tqdm): """Matplotlib GUI version."""
class tqdm.tk.tqdm(tqdm.tqdm): """Tkinter GUI version."""
class tqdm.rich.tqdm(tqdm.tqdm): """`rich.progress` version."""
class tqdm.keras.TqdmCallback(keras.callbacks.Callback): """Keras callback for epoch and batch progress."""
class tqdm.dask.TqdmCallback(dask.callbacks.Callback): """Dask callback for task progress."""
``contrib``+++++++++++
The ``tqdm.contrib`` package also contains experimental modules:
- ``tqdm.contrib.itertools``: Thin wrappers around ``itertools``- ``tqdm.contrib.concurrent``: Thin wrappers around ``concurrent.futures``- ``tqdm.contrib.slack``: Posts to `Slack <https://slack.com>`__ bots- ``tqdm.contrib.discord``: Posts to `Discord <https://discord.com>`__ bots- ``tqdm.contrib.telegram``: Posts to `Telegram <https://telegram.org>`__ bots- ``tqdm.contrib.bells``: Automagically enables all optional features
* ``auto``, ``pandas``, ``slack``, ``discord``, ``telegram``
Examples and Advanced Usage---------------------------
- See the `examples <https://github.com/tqdm/tqdm/tree/master/examples>`__ folder;- import the module and run ``help()``;- consult the `wiki <https://github.com/tqdm/tqdm/wiki>`__;
* this has an `excellent article <https://github.com/tqdm/tqdm/wiki/How-to-make-a-great-Progress-Bar>`__ on how to make a **great** progressbar;
- check out the `slides from PyData London <https://tqdm.github.io/PyData2019/slides.html>`__, or- run the |binder-demo|.
Description and additional stats~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Custom information can be displayed and updated dynamically on ``tqdm`` barswith the ``desc`` and ``postfix`` arguments:
.. code:: python
from tqdm import tqdm, trange from random import random, randint from time import sleep
with trange(10) as t: for i in t: # Description will be displayed on the left t.set_description('GEN %i' % i) # Postfix will be displayed on the right, # formatted automatically based on argument's datatype t.set_postfix(loss=random(), gen=randint(1,999), str='h', lst=[1, 2]) sleep(0.1)
with tqdm(total=10, bar_format="{postfix[0]} {postfix[1][value]:>8.2g}", postfix=["Batch", {"value": 0}]) as t: for i in range(10): sleep(0.1) t.postfix[1]["value"] = i / 2 t.update()
Points to remember when using ``{postfix[...]}`` in the ``bar_format`` string:
- ``postfix`` also needs to be passed as an initial argument in a compatible format, and- ``postfix`` will be auto-converted to a string if it is a ``dict``-like object. To prevent this behaviour, insert an extra item into the dictionary where the key is not a string.
Additional ``bar_format`` parameters may also be defined by overriding``format_dict``, and the bar itself may be modified using ``ascii``:
.. code:: python
from tqdm import tqdm class TqdmExtraFormat(tqdm): """Provides a `total_time` format parameter""" @property def format_dict(self): d = super().format_dict total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1) d.update(total_time=self.format_interval(total_time) + " in total") return d
for i in TqdmExtraFormat( range(9), ascii=" .oO0", bar_format="{total_time}: {percentage:.0f}%|{bar}{r_bar}"): if i == 4: break
.. code::
00:00 in total: 44%|0000. | 4/9 [00:00<00:00, 962.93it/s]
Note that ``{bar}`` also supports a format specifier ``[width][type]``.
- ``width``
* unspecified (default): automatic to fill ``ncols`` * ``int >= 0``: fixed width overriding ``ncols`` logic * ``int < 0``: subtract from the automatic default
- ``type``
* ``a``: ascii (``ascii=True`` override) * ``u``: unicode (``ascii=False`` override) * ``b``: blank (``ascii=" "`` override)
This means a fixed bar with right-justified text may be created by using:``bar_format="{l_bar}{bar:10}|{bar:-10b}right-justified"``
Nested progress bars~~~~~~~~~~~~~~~~~~~~
``tqdm`` supports nested progress bars. Here's an example:
.. code:: python
from tqdm.auto import trange from time import sleep
for i in trange(4, desc='1st loop'): for j in trange(5, desc='2nd loop'): for k in trange(50, desc='3rd loop', leave=False): sleep(0.01)
For manual control over positioning (e.g. for multi-processing use),you may specify ``position=n`` where ``n=0`` for the outermost bar,``n=1`` for the next, and so on.However, it's best to check if ``tqdm`` can work without manual ``position``first.
.. code:: python
from time import sleep from tqdm import trange, tqdm from multiprocessing import Pool, RLock, freeze_support
L = list(range(9))
def progresser(n): interval = 0.001 / (n + 2) total = 5000 text = f"#{n}, est. {interval * total:<04.2}s" for _ in trange(total, desc=text, position=n): sleep(interval)
if __name__ == '__main__': freeze_support() # for Windows support tqdm.set_lock(RLock()) # for managing output contention p = Pool(initializer=tqdm.set_lock, initargs=(tqdm.get_lock(),)) p.map(progresser, L)
Note that in Python 3, ``tqdm.write`` is thread-safe:
.. code:: python
from time import sleep from tqdm import tqdm, trange from concurrent.futures import ThreadPoolExecutor
L = list(range(9))
def progresser(n): interval = 0.001 / (n + 2) total = 5000 text = f"#{n}, est. {interval * total:<04.2}s" for _ in trange(total, desc=text): sleep(interval) if n == 6: tqdm.write("n == 6 completed.") tqdm.write("`tqdm.write()` is thread-safe in py3!")
if __name__ == '__main__': with ThreadPoolExecutor() as p: p.map(progresser, L)
Hooks and callbacks~~~~~~~~~~~~~~~~~~~
``tqdm`` can easily support callbacks/hooks and manual updates.Here's an example with ``urllib``:
**``urllib.urlretrieve`` documentation**
| [...] | If present, the hook function will be called once | on establishment of the network connection and once after each block read | thereafter. The hook will be passed three arguments; a count of blocks | transferred so far, a block size in bytes, and the total size of the file. | [...]
.. code:: python
import urllib, os from tqdm import tqdm urllib = getattr(urllib, 'request', urllib)
class TqdmUpTo(tqdm): """Provides `update_to(n)` which uses `tqdm.update(delta_n)`.""" def update_to(self, b=1, bsize=1, tsize=None): """ b : int, optional Number of blocks transferred so far [default: 1]. bsize : int, optional Size of each block (in tqdm units) [default: 1]. tsize : int, optional Total size (in tqdm units). If [default: None] remains unchanged. """ if tsize is not None: self.total = tsize return self.update(b * bsize - self.n) # also sets self.n = b * bsize
eg_link = "https://caspersci.uk.to/matryoshka.zip" with TqdmUpTo(unit='B', unit_scale=True, unit_divisor=1024, miniters=1, desc=eg_link.split('/')[-1]) as t: # all optional kwargs urllib.urlretrieve(eg_link, filename=os.devnull, reporthook=t.update_to, data=None) t.total = t.n
Inspired by `twine#242 <https://github.com/pypa/twine/pull/242>`__.Functional alternative in`examples/tqdm_wget.py <https://github.com/tqdm/tqdm/blob/master/examples/tqdm_wget.py>`__.
It is recommend to use ``miniters=1`` whenever there is potentiallylarge differences in iteration speed (e.g. downloading a file overa patchy connection).
**Wrapping read/write methods**
To measure throughput through a file-like object's ``read`` or ``write``methods, use ``CallbackIOWrapper``:
.. code:: python
from tqdm.auto import tqdm from tqdm.utils import CallbackIOWrapper
with tqdm(total=file_obj.size, unit='B', unit_scale=True, unit_divisor=1024) as t: fobj = CallbackIOWrapper(t.update, file_obj, "read") while True: chunk = fobj.read(chunk_size) if not chunk: break t.reset() # ... continue to use `t` for something else
Alternatively, use the even simpler ``wrapattr`` convenience function,which would condense both the ``urllib`` and ``CallbackIOWrapper`` examplesdown to:
.. code:: python
import urllib, os from tqdm import tqdm
eg_link = "https://caspersci.uk.to/matryoshka.zip" response = getattr(urllib, 'request', urllib).urlopen(eg_link) with tqdm.wrapattr(open(os.devnull, "wb"), "write", miniters=1, desc=eg_link.split('/')[-1], total=getattr(response, 'length', None)) as fout: for chunk in response: fout.write(chunk)
The ``requests`` equivalent is nearly identical:
.. code:: python
import requests, os from tqdm import tqdm
eg_link = "https://caspersci.uk.to/matryoshka.zip" response = requests.get(eg_link, stream=True) with tqdm.wrapattr(open(os.devnull, "wb"), "write", miniters=1, desc=eg_link.split('/')[-1], total=int(response.headers.get('content-length', 0))) as fout: for chunk in response.iter_content(chunk_size=4096): fout.write(chunk)
**Custom callback**
``tqdm`` is known for intelligently skipping unnecessary displays. To make acustom callback take advantage of this, simply use the return value of``update()``. This is set to ``True`` if a ``display()`` was triggered.
.. code:: python
from tqdm.auto import tqdm as std_tqdm
def external_callback(*args, **kwargs): ...
class TqdmExt(std_tqdm): def update(self, n=1): displayed = super().update(n) if displayed: external_callback(**self.format_dict) return displayed
``asyncio``~~~~~~~~~~~
Note that ``break`` isn't currently caught by asynchronous iterators.This means that ``tqdm`` cannot clean up after itself in this case:
.. code:: python
from tqdm.asyncio import tqdm
async for i in tqdm(range(9)): if i == 2: break
Instead, either call ``pbar.close()`` manually or use the context manager syntax:
.. code:: python
from tqdm.asyncio import tqdm
with tqdm(range(9)) as pbar: async for i in pbar: if i == 2: break
Pandas Integration~~~~~~~~~~~~~~~~~~
Due to popular demand we've added support for ``pandas`` -- here's an examplefor ``DataFrame.progress_apply`` and ``DataFrameGroupBy.progress_apply``:
.. code:: python
import pandas as pd import numpy as np from tqdm import tqdm
df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
# Register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm` # (can use `tqdm.gui.tqdm`, `tqdm.notebook.tqdm`, optional kwargs, etc.) tqdm.pandas(desc="my bar!")
# Now you can use `progress_apply` instead of `apply` # and `progress_map` instead of `map` df.progress_apply(lambda x: x**2) # can also groupby: # df.groupby(0).progress_apply(lambda x: x**2)
In case you're interested in how this works (and how to modify it for yourown callbacks), see the`examples <https://github.com/tqdm/tqdm/tree/master/examples>`__folder or import the module and run ``help()``.
Keras Integration~~~~~~~~~~~~~~~~~
A ``keras`` callback is also available:
.. code:: python
from tqdm.keras import TqdmCallback
...
model.fit(..., verbose=0, callbacks=[TqdmCallback()])
Dask Integration~~~~~~~~~~~~~~~~
A ``dask`` callback is also available:
.. code:: python
from tqdm.dask import TqdmCallback
with TqdmCallback(desc="compute"): ... arr.compute()
# or use callback globally cb = TqdmCallback(desc="global") cb.register() arr.compute()
IPython/Jupyter Integration~~~~~~~~~~~~~~~~~~~~~~~~~~~~
IPython/Jupyter is supported via the ``tqdm.notebook`` submodule:
.. code:: python
from tqdm.notebook import trange, tqdm from time import sleep
for i in trange(3, desc='1st loop'): for j in tqdm(range(100), desc='2nd loop'): sleep(0.01)
In addition to ``tqdm`` features, the submodule provides a native Jupyterwidget (compatible with IPython v1-v4 and Jupyter), fully working nested barsand colour hints (blue: normal, green: completed, red: error/interrupt,light blue: no ETA); as demonstrated below.
|Screenshot-Jupyter1||Screenshot-Jupyter2||Screenshot-Jupyter3|
The ``notebook`` version supports percentage or pixels for overall width(e.g.: ``ncols='100%'`` or ``ncols='480px'``).
It is also possible to let ``tqdm`` automatically choose betweenconsole or notebook versions by using the ``autonotebook`` submodule:
.. code:: python
from tqdm.autonotebook import tqdm tqdm.pandas()
Note that this will issue a ``TqdmExperimentalWarning`` if run in a notebooksince it is not meant to be possible to distinguish between ``jupyter notebook``and ``jupyter console``. Use ``auto`` instead of ``autonotebook`` to suppressthis warning.
Note that notebooks will display the bar in the cell where it was created.This may be a different cell from the one where it is used.If this is not desired, either
- delay the creation of the bar to the cell where it must be displayed, or- create the bar with ``display=False``, and in a later cell call ``display(bar.container)``:
.. code:: python
from tqdm.notebook import tqdm pbar = tqdm(..., display=False)
.. code:: python
# different cell display(pbar.container)
The ``keras`` callback has a ``display()`` method which can be used likewise:
.. code:: python
from tqdm.keras import TqdmCallback cbk = TqdmCallback(display=False)
.. code:: python
# different cell cbk.display() model.fit(..., verbose=0, callbacks=[cbk])
Another possibility is to have a single bar (near the top of the notebook)which is constantly re-used (using ``reset()`` rather than ``close()``).For this reason, the notebook version (unlike the CLI version) does notautomatically call ``close()`` upon ``Exception``.
.. code:: python
from tqdm.notebook import tqdm pbar = tqdm()
.. code:: python
# different cell iterable = range(100) pbar.reset(total=len(iterable)) # initialise with new `total` for i in iterable: pbar.update() pbar.refresh() # force print final status but don't `close()`
Custom Integration~~~~~~~~~~~~~~~~~~
To change the default arguments (such as making ``dynamic_ncols=True``),simply use built-in Python magic:
.. code:: python
from functools import partial from tqdm import tqdm as std_tqdm tqdm = partial(std_tqdm, dynamic_ncols=True)
For further customisation,``tqdm`` may be inherited from to create custom callbacks (as with the``TqdmUpTo`` example `above <#hooks-and-callbacks>`__) or for custom frontends(e.g. GUIs such as notebook or plotting packages). In the latter case:
1. ``def __init__()`` to call ``super().__init__(..., gui=True)`` to disable terminal ``status_printer`` creation.2. Redefine: ``close()``, ``clear()``, ``display()``.
Consider overloading ``display()`` to use e.g.``self.frontend(**self.format_dict)`` instead of ``self.sp(repr(self))``.
Some submodule examples of inheritance:
- `tqdm/notebook.py <https://github.com/tqdm/tqdm/blob/master/tqdm/notebook.py>`__- `tqdm/gui.py <https://github.com/tqdm/tqdm/blob/master/tqdm/gui.py>`__- `tqdm/tk.py <https://github.com/tqdm/tqdm/blob/master/tqdm/tk.py>`__- `tqdm/contrib/slack.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/slack.py>`__- `tqdm/contrib/discord.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/discord.py>`__- `tqdm/contrib/telegram.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/telegram.py>`__
Dynamic Monitor/Meter~~~~~~~~~~~~~~~~~~~~~
You can use a ``tqdm`` as a meter which is not monotonically increasing.This could be because ``n`` decreases (e.g. a CPU usage monitor) or ``total``changes.
One example would be recursively searching for files. The ``total`` is thenumber of objects found so far, while ``n`` is the number of those objects whichare files (rather than folders):
.. code:: python
from tqdm import tqdm import os.path
def find_files_recursively(path, show_progress=True): files = [] # total=1 assumes `path` is a file t = tqdm(total=1, unit="file", disable=not show_progress) if not os.path.exists(path): raise IOError("Cannot find:" + path)
def append_found_file(f): files.append(f) t.update()
def list_found_dir(path): """returns os.listdir(path) assuming os.path.isdir(path)""" listing = os.listdir(path) # subtract 1 since a "file" we found was actually this directory t.total += len(listing) - 1 # fancy way to give info without forcing a refresh t.set_postfix(dir=path[-10:], refresh=False) t.update(0) # may trigger a refresh return listing
def recursively_search(path): if os.path.isdir(path): for f in list_found_dir(path): recursively_search(os.path.join(path, f)) else: append_found_file(path)
recursively_search(path) t.set_postfix(dir=path) t.close() return files
Using ``update(0)`` is a handy way to let ``tqdm`` decide when to trigger adisplay refresh to avoid console spamming.
Writing messages~~~~~~~~~~~~~~~~
This is a work in progress (see`#737 <https://github.com/tqdm/tqdm/issues/737>`__).
Since ``tqdm`` uses a simple printing mechanism to display progress bars,you should not write any message in the terminal using ``print()`` whilea progressbar is open.
To write messages in the terminal without any collision with ``tqdm`` bardisplay, a ``.write()`` method is provided:
.. code:: python
from tqdm.auto import tqdm, trange from time import sleep
bar = trange(10) for i in bar: # Print using tqdm class method .write() sleep(0.1) if not (i % 3): tqdm.write("Done task %i" % i) # Can also use bar.write()
By default, this will print to standard output ``sys.stdout``. but you canspecify any file-like object using the ``file`` argument. For example, thiscan be used to redirect the messages writing to a log file or class.
Redirecting writing~~~~~~~~~~~~~~~~~~~
If using a library that can print messages to the console, editing the libraryby replacing ``print()`` with ``tqdm.write()`` may not be desirable.In that case, redirecting ``sys.stdout`` to ``tqdm.write()`` is an option.
To redirect ``sys.stdout``, create a file-like class that will writeany input string to ``tqdm.write()``, and supply the arguments``file=sys.stdout, dynamic_ncols=True``.
A reusable canonical example is given below:
.. code:: python
from time import sleep import contextlib import sys from tqdm import tqdm from tqdm.contrib import DummyTqdmFile
@contextlib.contextmanager def std_out_err_redirect_tqdm(): orig_out_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = map(DummyTqdmFile, orig_out_err) yield orig_out_err[0] # Relay exceptions except Exception as exc: raise exc # Always restore sys.stdout/err if necessary finally: sys.stdout, sys.stderr = orig_out_err
def some_fun(i): print("Fee, fi, fo,".split()[i])
# Redirect stdout to tqdm.write() (don't forget the `as save_stdout`) with std_out_err_redirect_tqdm() as orig_stdout: # tqdm needs the original stdout # and dynamic_ncols=True to autodetect console width for i in tqdm(range(3), file=orig_stdout, dynamic_ncols=True): sleep(.5) some_fun(i)
# After the `with`, printing is restored print("Done!")
Redirecting ``logging``~~~~~~~~~~~~~~~~~~~~~~~
Similar to ``sys.stdout``/``sys.stderr`` as detailed above, console ``logging``may also be redirected to ``tqdm.write()``.
Warning: if also redirecting ``sys.stdout``/``sys.stderr``, make sure toredirect ``logging`` first if needed.
Helper methods are available in ``tqdm.contrib.logging``. For example:
.. code:: python
import logging from tqdm import trange from tqdm.contrib.logging import logging_redirect_tqdm
LOG = logging.getLogger(__name__)
if __name__ == '__main__': logging.basicConfig(level=logging.INFO) with logging_redirect_tqdm(): for i in trange(9): if i == 4: LOG.info("console logging redirected to `tqdm.write()`") # logging restored
Monitoring thread, intervals and miniters~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``tqdm`` implements a few tricks to increase efficiency and reduce overhead.
- Avoid unnecessary frequent bar refreshing: ``mininterval`` defines how long to wait between each refresh. ``tqdm`` always gets updated in the background, but it will display only every ``mininterval``.- Reduce number of calls to check system clock/time.- ``mininterval`` is more intuitive to configure than ``miniters``. A clever adjustment system ``dynamic_miniters`` will automatically adjust ``miniters`` to the amount of iterations that fit into time ``mininterval``. Essentially, ``tqdm`` will check if it's time to print without actually checking time. This behaviour can be still be bypassed by manually setting ``miniters``.
However, consider a case with a combination of fast and slow iterations.After a few fast iterations, ``dynamic_miniters`` will set ``miniters`` to alarge number. When iteration rate subsequently slows, ``miniters`` willremain large and thus reduce display update frequency. To address this:
- ``maxinterval`` defines the maximum time between display refreshes. A concurrent monitoring thread checks for overdue updates and forces one where necessary.
The monitoring thread should not have a noticeable overhead, and guaranteesupdates at least every 10 seconds by default.This value can be directly changed by setting the ``monitor_interval`` ofany ``tqdm`` instance (i.e. ``t = tqdm.tqdm(...); t.monitor_interval = 2``).The monitor thread may be disabled application-wide by setting``tqdm.tqdm.monitor_interval = 0`` before instantiation of any ``tqdm`` bar.
Merch-----
You can buy `tqdm branded merch <https://tqdm.github.io/merch>`__ now!
Contributions-------------
|GitHub-Commits| |GitHub-Issues| |GitHub-PRs| |OpenHub-Status| |GitHub-Contributions| |CII Best Practices|
All source code is hosted on `GitHub <https://github.com/tqdm/tqdm>`__.Contributions are welcome.
See the`CONTRIBUTING <https://github.com/tqdm/tqdm/blob/master/CONTRIBUTING.md>`__file for more information.
Developers who have made significant contributions, ranked by *SLoC*(surviving lines of code,`git fame <https://github.com/casperdcl/git-fame>`__ ``-wMC --excl '\.(png|gif|jpg)$'``),are:
==================== ======================================================== ==== ================================Name ID SLoC Notes==================== ======================================================== ==== ================================Casper da Costa-Luis `casperdcl <https://github.com/casperdcl>`__ ~80% primary maintainer |Gift-Casper|Stephen Larroque `lrq3000 <https://github.com/lrq3000>`__ ~9% team memberMartin Zugnoni `martinzugnoni <https://github.com/martinzugnoni>`__ ~3%Daniel Ecer `de-code <https://github.com/de-code>`__ ~2%Richard Sheridan `richardsheridan <https://github.com/richardsheridan>`__ ~1%Guangshuo Chen `chengs <https://github.com/chengs>`__ ~1%Helio Machado `0x2b3bfa0 <https://github.com/0x2b3bfa0>`__ ~1%Kyle Altendorf `altendky <https://github.com/altendky>`__ <1%Noam Yorav-Raphael `noamraph <https://github.com/noamraph>`__ <1% original authorMatthew Stevens `mjstevens777 <https://github.com/mjstevens777>`__ <1%Hadrien Mary `hadim <https://github.com/hadim>`__ <1% team memberMikhail Korobov `kmike <https://github.com/kmike>`__ <1% team member==================== ======================================================== ==== ================================
Ports to Other Languages~~~~~~~~~~~~~~~~~~~~~~~~
A list is available on`this wiki page <https://github.com/tqdm/tqdm/wiki/tqdm-ports>`__.
LICENCE-------
Open Source (OSI approved): |LICENCE|
Citation information: |DOI|
|README-Hits| (Since 19 May 2016)
.. |Logo| image:: https://tqdm.github.io/img/logo.gif.. |Screenshot| image:: https://tqdm.github.io/img/tqdm.gif.. |Video| image:: https://tqdm.github.io/img/video.jpg :target: https://tqdm.github.io/video.. |Slides| image:: https://tqdm.github.io/img/slides.jpg :target: https://tqdm.github.io/PyData2019/slides.html.. |Merch| image:: https://tqdm.github.io/img/merch.jpg :target: https://tqdm.github.io/merch.. |Build-Status| image:: https://img.shields.io/github/actions/workflow/status/tqdm/tqdm/test.yml?branch=master&label=tqdm&logo=GitHub :target: https://github.com/tqdm/tqdm/actions/workflows/test.yml.. |Coverage-Status| image:: https://img.shields.io/coveralls/github/tqdm/tqdm/master?logo=coveralls :target: https://coveralls.io/github/tqdm/tqdm.. |Branch-Coverage-Status| image:: https://codecov.io/gh/tqdm/tqdm/branch/master/graph/badge.svg :target: https://codecov.io/gh/tqdm/tqdm.. |Codacy-Grade| image:: https://app.codacy.com/project/badge/Grade/3f965571598f44549c7818f29cdcf177 :target: https://www.codacy.com/gh/tqdm/tqdm/dashboard.. |CII Best Practices| image:: https://bestpractices.coreinfrastructure.org/projects/3264/badge :target: https://bestpractices.coreinfrastructure.org/projects/3264.. |GitHub-Status| image:: https://img.shields.io/github/tag/tqdm/tqdm.svg?maxAge=86400&logo=github&logoColor=white :target: https://github.com/tqdm/tqdm/releases.. |GitHub-Forks| image:: https://img.shields.io/github/forks/tqdm/tqdm.svg?logo=github&logoColor=white :target: https://github.com/tqdm/tqdm/network.. |GitHub-Stars| image:: https://img.shields.io/github/stars/tqdm/tqdm.svg?logo=github&logoColor=white :target: https://github.com/tqdm/tqdm/stargazers.. |GitHub-Commits| image:: https://img.shields.io/github/commit-activity/y/tqdm/tqdm.svg?logo=git&logoColor=white :target: https://github.com/tqdm/tqdm/graphs/commit-activity.. |GitHub-Issues| image:: https://img.shields.io/github/issues-closed/tqdm/tqdm.svg?logo=github&logoColor=white :target: https://github.com/tqdm/tqdm/issues?q=.. |GitHub-PRs| image:: https://img.shields.io/github/issues-pr-closed/tqdm/tqdm.svg?logo=github&logoColor=white :target: https://github.com/tqdm/tqdm/pulls.. |GitHub-Contributions| image:: https://img.shields.io/github/contributors/tqdm/tqdm.svg?logo=github&logoColor=white :target: https://github.com/tqdm/tqdm/graphs/contributors.. |GitHub-Updated| image:: https://img.shields.io/github/last-commit/tqdm/tqdm/master.svg?logo=github&logoColor=white&label=pushed :target: https://github.com/tqdm/tqdm/pulse.. |Gift-Casper| image:: https://img.shields.io/badge/dynamic/json.svg?color=ff69b4&label=gifts%20received&prefix=%C2%A3&query=%24..sum&url=https%3A%2F%2Fcaspersci.uk.to%2Fgifts.json :target: https://cdcl.ml/sponsor.. |Versions| image:: https://img.shields.io/pypi/v/tqdm.svg :target: https://tqdm.github.io/releases.. |PyPI-Downloads| image:: https://img.shields.io/pypi/dm/tqdm.svg?label=pypi%20downloads&logo=PyPI&logoColor=white :target: https://pepy.tech/project/tqdm.. |Py-Versions| image:: https://img.shields.io/pypi/pyversions/tqdm.svg?logo=python&logoColor=white :target: https://pypi.org/project/tqdm.. |Conda-Forge-Status| image:: https://img.shields.io/conda/v/conda-forge/tqdm.svg?label=conda-forge&logo=conda-forge :target: https://anaconda.org/conda-forge/tqdm.. |Snapcraft| image:: https://img.shields.io/badge/snap-install-82BEA0.svg?logo=snapcraft :target: https://snapcraft.io/tqdm.. |Docker| image:: https://img.shields.io/badge/docker-pull-blue.svg?logo=docker&logoColor=white :target: https://hub.docker.com/r/tqdm/tqdm.. |Libraries-Rank| image:: https://img.shields.io/librariesio/sourcerank/pypi/tqdm.svg?logo=koding&logoColor=white :target: https://libraries.io/pypi/tqdm.. |Libraries-Dependents| image:: https://img.shields.io/librariesio/dependent-repos/pypi/tqdm.svg?logo=koding&logoColor=white :target: https://github.com/tqdm/tqdm/network/dependents.. |OpenHub-Status| image:: https://www.openhub.net/p/tqdm/widgets/project_thin_badge?format=gif :target: https://www.openhub.net/p/tqdm?ref=Thin+badge.. |awesome-python| image:: https://awesome.re/mentioned-badge.svg :target: https://github.com/vinta/awesome-python.. |LICENCE| image:: https://img.shields.io/pypi/l/tqdm.svg :target: https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE.. |DOI| image:: https://img.shields.io/badge/DOI-10.5281/zenodo.595120-blue.svg :target: https://doi.org/10.5281/zenodo.595120.. |binder-demo| image:: https://mybinder.org/badge_logo.svg :target: https://mybinder.org/v2/gh/tqdm/tqdm/master?filepath=DEMO.ipynb.. |Screenshot-Jupyter1| image:: https://tqdm.github.io/img/jupyter-1.gif.. |Screenshot-Jupyter2| image:: https://tqdm.github.io/img/jupyter-2.gif.. |Screenshot-Jupyter3| image:: https://tqdm.github.io/img/jupyter-3.gif.. |README-Hits| image:: https://cgi.cdcl.ml/hits?q=tqdm&style=social&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif :target: https://cgi.cdcl.ml/hits?q=tqdm&a=plot&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif&style=social123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329Metadata-Version: 2.4Name: huggingface_hubVersion: 1.16.4Summary: Client library to download and publish models, datasets and other repos on the huggingface.co hubHome-page: https://github.com/huggingface/huggingface_hubAuthor: Hugging Face, Inc.Author-email: julien@huggingface.coLicense: Apache-2.0Keywords: model-hub machine-learning models natural-language-processing deep-learning pytorch pretrained-modelsClassifier: Intended Audience :: DevelopersClassifier: Intended Audience :: EducationClassifier: Intended Audience :: Science/ResearchClassifier: License :: OSI Approved :: Apache Software LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Topic :: Scientific/Engineering :: Artificial IntelligenceRequires-Python: >=3.10.0Description-Content-Type: text/markdownLicense-File: LICENSERequires-Dist: click>=8.4.0Requires-Dist: filelock>=3.10.0Requires-Dist: fsspec>=2023.5.0Requires-Dist: hf-xet<2.0.0,>=1.4.3; platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "arm64" or platform_machine == "aarch64"Requires-Dist: httpx<1,>=0.23.0Requires-Dist: packaging>=20.9Requires-Dist: pyyaml>=5.1Requires-Dist: tqdm>=4.42.1Requires-Dist: typer<0.26.0,>=0.20.0Requires-Dist: typing-extensions>=4.1.0Provides-Extra: oauthRequires-Dist: authlib>=1.3.2; extra == "oauth"Requires-Dist: fastapi; extra == "oauth"Requires-Dist: httpx; extra == "oauth"Requires-Dist: itsdangerous; extra == "oauth"Provides-Extra: torchRequires-Dist: torch; extra == "torch"Requires-Dist: safetensors[torch]; extra == "torch"Provides-Extra: fastaiRequires-Dist: toml; extra == "fastai"Requires-Dist: fastai>=2.4; extra == "fastai"Requires-Dist: fastcore>=1.3.27; extra == "fastai"Provides-Extra: hf-xetRequires-Dist: hf-xet<2.0.0,>=1.4.3; extra == "hf-xet"Provides-Extra: mcpRequires-Dist: mcp>=1.8.0; extra == "mcp"Provides-Extra: testingRequires-Dist: authlib>=1.3.2; extra == "testing"Requires-Dist: fastapi; extra == "testing"Requires-Dist: httpx; extra == "testing"Requires-Dist: itsdangerous; extra == "testing"Requires-Dist: jedi; extra == "testing"Requires-Dist: Jinja2; extra == "testing"Requires-Dist: pytest>=8.4.2; extra == "testing"Requires-Dist: pytest-cov; extra == "testing"Requires-Dist: pytest-env; extra == "testing"Requires-Dist: pytest-xdist; extra == "testing"Requires-Dist: pytest-vcr; extra == "testing"Requires-Dist: pytest-asyncio; extra == "testing"Requires-Dist: pytest-rerunfailures<16.0; extra == "testing"Requires-Dist: pytest-mock; extra == "testing"Requires-Dist: urllib3<2.0; extra == "testing"Requires-Dist: soundfile; extra == "testing"Requires-Dist: Pillow; extra == "testing"Requires-Dist: numpy; extra == "testing"Requires-Dist: duckdb; extra == "testing"Requires-Dist: fastapi; extra == "testing"Provides-Extra: gradioRequires-Dist: gradio>=5.0.0; extra == "gradio"Requires-Dist: requests; extra == "gradio"Provides-Extra: typingRequires-Dist: typing-extensions>=4.8.0; extra == "typing"Requires-Dist: types-PyYAML; extra == "typing"Requires-Dist: types-simplejson; extra == "typing"Requires-Dist: types-toml; extra == "typing"Requires-Dist: types-tqdm; extra == "typing"Requires-Dist: types-urllib3; extra == "typing"Provides-Extra: qualityRequires-Dist: ruff>=0.9.0; extra == "quality"Requires-Dist: mypy==1.15.0; extra == "quality"Requires-Dist: libcst>=1.4.0; extra == "quality"Requires-Dist: ty; extra == "quality"Provides-Extra: allRequires-Dist: authlib>=1.3.2; extra == "all"Requires-Dist: fastapi; extra == "all"Requires-Dist: httpx; extra == "all"Requires-Dist: itsdangerous; extra == "all"Requires-Dist: jedi; extra == "all"Requires-Dist: Jinja2; extra == "all"Requires-Dist: pytest>=8.4.2; extra == "all"Requires-Dist: pytest-cov; extra == "all"Requires-Dist: pytest-env; extra == "all"Requires-Dist: pytest-xdist; extra == "all"Requires-Dist: pytest-vcr; extra == "all"Requires-Dist: pytest-asyncio; extra == "all"Requires-Dist: pytest-rerunfailures<16.0; extra == "all"Requires-Dist: pytest-mock; extra == "all"Requires-Dist: urllib3<2.0; extra == "all"Requires-Dist: soundfile; extra == "all"Requires-Dist: Pillow; extra == "all"Requires-Dist: numpy; extra == "all"Requires-Dist: duckdb; extra == "all"Requires-Dist: fastapi; extra == "all"Requires-Dist: ruff>=0.9.0; extra == "all"Requires-Dist: mypy==1.15.0; extra == "all"Requires-Dist: libcst>=1.4.0; extra == "all"Requires-Dist: ty; extra == "all"Requires-Dist: typing-extensions>=4.8.0; extra == "all"Requires-Dist: types-PyYAML; extra == "all"Requires-Dist: types-simplejson; extra == "all"Requires-Dist: types-toml; extra == "all"Requires-Dist: types-tqdm; extra == "all"Requires-Dist: types-urllib3; extra == "all"Provides-Extra: devRequires-Dist: authlib>=1.3.2; extra == "dev"Requires-Dist: fastapi; extra == "dev"Requires-Dist: httpx; extra == "dev"Requires-Dist: itsdangerous; extra == "dev"Requires-Dist: jedi; extra == "dev"Requires-Dist: Jinja2; extra == "dev"Requires-Dist: pytest>=8.4.2; extra == "dev"Requires-Dist: pytest-cov; extra == "dev"Requires-Dist: pytest-env; extra == "dev"Requires-Dist: pytest-xdist; extra == "dev"Requires-Dist: pytest-vcr; extra == "dev"Requires-Dist: pytest-asyncio; extra == "dev"Requires-Dist: pytest-rerunfailures<16.0; extra == "dev"Requires-Dist: pytest-mock; extra == "dev"Requires-Dist: urllib3<2.0; extra == "dev"Requires-Dist: soundfile; extra == "dev"Requires-Dist: Pillow; extra == "dev"Requires-Dist: numpy; extra == "dev"Requires-Dist: duckdb; extra == "dev"Requires-Dist: fastapi; extra == "dev"Requires-Dist: ruff>=0.9.0; extra == "dev"Requires-Dist: mypy==1.15.0; extra == "dev"Requires-Dist: libcst>=1.4.0; extra == "dev"Requires-Dist: ty; extra == "dev"Requires-Dist: typing-extensions>=4.8.0; extra == "dev"Requires-Dist: types-PyYAML; extra == "dev"Requires-Dist: types-simplejson; extra == "dev"Requires-Dist: types-toml; extra == "dev"Requires-Dist: types-tqdm; extra == "dev"Requires-Dist: types-urllib3; extra == "dev"Dynamic: authorDynamic: author-emailDynamic: classifierDynamic: descriptionDynamic: description-content-typeDynamic: home-pageDynamic: keywordsDynamic: licenseDynamic: license-fileDynamic: provides-extraDynamic: requires-distDynamic: requires-pythonDynamic: summary
<p align="center"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub-dark.svg"> <source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg"> <img alt="huggingface_hub library logo" src="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg" width="352" height="59" style="max-width: 100%"> </picture> <br/> <br/></p>
<p align="center"> <i>The official Python client for the Huggingface Hub.</i></p>
<p align="center"> <a href="https://huggingface.co/docs/huggingface_hub/en/index"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/huggingface_hub/index.svg?down_color=red&down_message=offline&up_message=online&label=doc"></a> <a href="https://github.com/huggingface/huggingface_hub/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/huggingface_hub.svg"></a> <a href="https://github.com/huggingface/huggingface_hub"><img alt="PyPi version" src="https://img.shields.io/pypi/pyversions/huggingface_hub.svg"></a> <a href="https://pypi.org/project/huggingface-hub"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/huggingface_hub"></a> <a href="https://codecov.io/gh/huggingface/huggingface_hub"><img alt="Code coverage" src="https://codecov.io/gh/huggingface/huggingface_hub/branch/main/graph/badge.svg?token=RXP95LE2XL"></a></p>
<h4 align="center"> <p> <b>English</b> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_de.md">Deutsch</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_fr.md">Français</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_hi.md">हिंदी</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_ko.md">한국어</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_cn.md">中文 (简体)</a> <p></h4>
---
**Documentation**: <a href="https://hf.co/docs/huggingface_hub" target="_blank">https://hf.co/docs/huggingface_hub</a>
**Source Code**: <a href="https://github.com/huggingface/huggingface_hub" target="_blank">https://github.com/huggingface/huggingface_hub</a>
---
## Welcome to the huggingface_hub library
The `huggingface_hub` library allows you to interact with the [Hugging Face Hub](https://huggingface.co/), a platform democratizing open-source Machine Learning for creators and collaborators. Discover pre-trained models and datasets for your projects or play with the thousands of machine learning apps hosted on the Hub. You can also create and share your own models, datasets and demos with the community. The `huggingface_hub` library provides a simple way to do all these things with Python.
## Key features
- [Download files](https://huggingface.co/docs/huggingface_hub/en/guides/download) from the Hub.- [Upload files](https://huggingface.co/docs/huggingface_hub/en/guides/upload) to the Hub.- [Manage your repositories](https://huggingface.co/docs/huggingface_hub/en/guides/repository).- [Run Inference](https://huggingface.co/docs/huggingface_hub/en/guides/inference) on deployed models.- [Search](https://huggingface.co/docs/huggingface_hub/en/guides/search) for models, datasets and Spaces.- [Share Model Cards](https://huggingface.co/docs/huggingface_hub/en/guides/model-cards) to document your models.- [Engage with the community](https://huggingface.co/docs/huggingface_hub/en/guides/community) through PRs and comments.
## Installation
Install the `huggingface_hub` package with [pip](https://pypi.org/project/huggingface-hub/):
```bashpip install huggingface_hub```
We recommend using [`uv`](https://docs.astral.sh/uv/) for a fast and reliable install:
```bashuv pip install huggingface_hub```
In order to keep the package minimal by default, `huggingface_hub` comes with optional dependencies useful for some use cases. For example, if you want to use the MCP module, run:
```bashpip install "huggingface_hub[mcp]"```
To learn more about installation and optional dependencies, check out the [installation guide](https://huggingface.co/docs/huggingface_hub/en/installation).
## Quick start
### Download files
Download a single file
```pyfrom huggingface_hub import hf_hub_download
hf_hub_download(repo_id="tiiuae/falcon-7b-instruct", filename="config.json")```
Or an entire repository
```pyfrom huggingface_hub import snapshot_download
snapshot_download("stabilityai/stable-diffusion-2-1")```
Files will be downloaded in a local cache folder. More details in [this guide](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache).
### Login
The Hugging Face Hub uses tokens to authenticate applications (see [docs](https://huggingface.co/docs/hub/security-tokens)). To log in your machine, run the following CLI:
```bashhf auth login# or using an environment variablehf auth login --token $HUGGINGFACE_TOKEN```
### Create a repository
```pyfrom huggingface_hub import create_repo
create_repo(repo_id="super-cool-model")```
### Upload files
Upload a single file
```pyfrom huggingface_hub import upload_file
upload_file( path_or_fileobj="/home/lysandre/dummy-test/README.md", path_in_repo="README.md", repo_id="lysandre/test-model",)```
Or an entire folder
```pyfrom huggingface_hub import upload_folder
upload_folder( folder_path="/path/to/local/space", repo_id="username/my-cool-space", repo_type="space",)```
For details in the [upload guide](https://huggingface.co/docs/huggingface_hub/en/guides/upload).
## Integrating to the Hub.
We're partnering with cool open source ML libraries to provide free model hosting and versioning. You can find the existing integrations [here](https://huggingface.co/docs/hub/libraries).
The advantages are:
- Free model or dataset hosting for libraries and their users.- Built-in file versioning, even with very large files, thanks to a git-based approach.- In-browser widgets to play with the uploaded models.- Anyone can upload a new model for your library, they just need to add the corresponding tag for the model to be discoverable.- Fast downloads! We use Cloudfront (a CDN) to geo-replicate downloads so they're blazing fast from anywhere on the globe.- Usage stats and more features to come.
If you would like to integrate your library, feel free to open an issue to begin the discussion. We wrote a [step-by-step guide](https://huggingface.co/docs/hub/adding-a-library) with ❤️ showing how to do this integration.
## Contributions (feature requests, bugs, etc.) are super welcome 💙💚💛💜🧡❤️
Everyone is welcome to contribute, and we value everybody's contribution. Code is not the only way to help the community.Answering questions, helping others, reaching out and improving the documentations are immensely valuable to the community.We wrote a [contribution guide](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) to summarizehow to get started to contribute to this repository.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586Metadata-Version: 2.1Name: openpyxlVersion: 3.1.5Summary: A Python library to read/write Excel 2010 xlsx/xlsm filesHome-page: https://openpyxl.readthedocs.ioAuthor: See AUTHORSAuthor-email: charlie.clark@clark-consulting.euLicense: MITProject-URL: Documentation, https://openpyxl.readthedocs.io/en/stable/Project-URL: Source, https://foss.heptapod.net/openpyxl/openpyxlProject-URL: Tracker, https://foss.heptapod.net/openpyxl/openpyxl/-/issuesClassifier: Development Status :: 5 - Production/StableClassifier: Operating System :: MacOS :: MacOS XClassifier: Operating System :: Microsoft :: WindowsClassifier: Operating System :: POSIXClassifier: License :: OSI Approved :: MIT LicenseClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3.6Classifier: Programming Language :: Python :: 3.7Classifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Requires-Python: >=3.8License-File: LICENCE.rstRequires-Dist: et-xmlfile
.. image:: https://coveralls.io/repos/bitbucket/openpyxl/openpyxl/badge.svg?branch=default :target: https://coveralls.io/bitbucket/openpyxl/openpyxl?branch=default :alt: coverage status
Introduction------------
openpyxl is a Python library to read/write Excel 2010 xlsx/xlsm/xltx/xltm files.
It was born from lack of existing library to read/write natively from Pythonthe Office Open XML format.
All kudos to the PHPExcel team as openpyxl was initially based on PHPExcel.
Security--------
By default openpyxl does not guard against quadratic blowup or billion laughsxml attacks. To guard against these attacks install defusedxml.
Mailing List------------
The user list can be found on http://groups.google.com/group/openpyxl-users
Sample code::
from openpyxl import Workbook wb = Workbook()
# grab the active worksheet ws = wb.active
# Data can be assigned directly to cells ws['A1'] = 42
# Rows can also be appended ws.append([1, 2, 3])
# Python types will automatically be converted import datetime ws['A2'] = datetime.datetime.now()
# Save the file wb.save("sample.xlsx")
Documentation-------------
The documentation is at: https://openpyxl.readthedocs.io
* installation methods* code examples* instructions for contributing
Release notes: https://openpyxl.readthedocs.io/en/stable/changes.html123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907Metadata-Version: 2.1Name: matplotlibVersion: 3.10.9Summary: Python plotting packageAuthor: John D. Hunter, Michael DroettboomAuthor-Email: Unknown <matplotlib-users@python.org>License: License agreement for matplotlib versions 1.3.0 and later ========================================================= 1. This LICENSE AGREEMENT is between the Matplotlib Development Team ("MDT"), and the Individual or Organization ("Licensee") accessing and otherwise using matplotlib software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, MDT hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use matplotlib alone or in any derivative version, provided, however, that MDT's License Agreement and MDT's notice of copyright, i.e., "Copyright (c) 2012- Matplotlib Development Team; All Rights Reserved" are retained in matplotlib alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to matplotlib . 4. MDT is making matplotlib available to Licensee on an "AS IS" basis. MDT MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, MDT MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. MDT SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING MATPLOTLIB , OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between MDT and Licensee. This License Agreement does not grant permission to use MDT trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using matplotlib , Licensee agrees to be bound by the terms and conditions of this License Agreement. License agreement for matplotlib versions prior to 1.3.0 ======================================================== 1. This LICENSE AGREEMENT is between John D. Hunter ("JDH"), and the Individual or Organization ("Licensee") accessing and otherwise using matplotlib software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, JDH hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use matplotlib alone or in any derivative version, provided, however, that JDH's License Agreement and JDH's notice of copyright, i.e., "Copyright (c) 2002-2011 John D. Hunter; All Rights Reserved" are retained in matplotlib alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to matplotlib. 4. JDH is making matplotlib available to Licensee on an "AS IS" basis. JDH MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, JDH MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING MATPLOTLIB , OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between JDH and Licensee. This License Agreement does not grant permission to use JDH trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using matplotlib, Licensee agrees to be bound by the terms and conditions of this License Agreement. ---- This binary distrubution of Matplotlib can also bundle the following software (depending on the build): Name: AMS Fonts Files: matplotlib/tests/cmr10.pfb Description: Type-1 version of one of Knuth's Computer Modern fonts License: OFL-1.1 The cmr10.pfb file is a Type-1 version of one of Knuth's Computer Modern fonts. It is included here as test data only, but the following license applies. Copyright (c) 1997, 2009, American Mathematical Society (http://www.ams.org). All Rights Reserved. "cmb10" is a Reserved Font Name for this Font Software. "cmbsy10" is a Reserved Font Name for this Font Software. "cmbsy5" is a Reserved Font Name for this Font Software. "cmbsy6" is a Reserved Font Name for this Font Software. "cmbsy7" is a Reserved Font Name for this Font Software. "cmbsy8" is a Reserved Font Name for this Font Software. "cmbsy9" is a Reserved Font Name for this Font Software. "cmbx10" is a Reserved Font Name for this Font Software. "cmbx12" is a Reserved Font Name for this Font Software. "cmbx5" is a Reserved Font Name for this Font Software. "cmbx6" is a Reserved Font Name for this Font Software. "cmbx7" is a Reserved Font Name for this Font Software. "cmbx8" is a Reserved Font Name for this Font Software. "cmbx9" is a Reserved Font Name for this Font Software. "cmbxsl10" is a Reserved Font Name for this Font Software. "cmbxti10" is a Reserved Font Name for this Font Software. "cmcsc10" is a Reserved Font Name for this Font Software. "cmcsc8" is a Reserved Font Name for this Font Software. "cmcsc9" is a Reserved Font Name for this Font Software. "cmdunh10" is a Reserved Font Name for this Font Software. "cmex10" is a Reserved Font Name for this Font Software. "cmex7" is a Reserved Font Name for this Font Software. "cmex8" is a Reserved Font Name for this Font Software. "cmex9" is a Reserved Font Name for this Font Software. "cmff10" is a Reserved Font Name for this Font Software. "cmfi10" is a Reserved Font Name for this Font Software. "cmfib8" is a Reserved Font Name for this Font Software. "cminch" is a Reserved Font Name for this Font Software. "cmitt10" is a Reserved Font Name for this Font Software. "cmmi10" is a Reserved Font Name for this Font Software. "cmmi12" is a Reserved Font Name for this Font Software. "cmmi5" is a Reserved Font Name for this Font Software. "cmmi6" is a Reserved Font Name for this Font Software. "cmmi7" is a Reserved Font Name for this Font Software. "cmmi8" is a Reserved Font Name for this Font Software. "cmmi9" is a Reserved Font Name for this Font Software. "cmmib10" is a Reserved Font Name for this Font Software. "cmmib5" is a Reserved Font Name for this Font Software. "cmmib6" is a Reserved Font Name for this Font Software. "cmmib7" is a Reserved Font Name for this Font Software. "cmmib8" is a Reserved Font Name for this Font Software. "cmmib9" is a Reserved Font Name for this Font Software. "cmr10" is a Reserved Font Name for this Font Software. "cmr12" is a Reserved Font Name for this Font Software. "cmr17" is a Reserved Font Name for this Font Software. "cmr5" is a Reserved Font Name for this Font Software. "cmr6" is a Reserved Font Name for this Font Software. "cmr7" is a Reserved Font Name for this Font Software. "cmr8" is a Reserved Font Name for this Font Software. "cmr9" is a Reserved Font Name for this Font Software. "cmsl10" is a Reserved Font Name for this Font Software. "cmsl12" is a Reserved Font Name for this Font Software. "cmsl8" is a Reserved Font Name for this Font Software. "cmsl9" is a Reserved Font Name for this Font Software. "cmsltt10" is a Reserved Font Name for this Font Software. "cmss10" is a Reserved Font Name for this Font Software. "cmss12" is a Reserved Font Name for this Font Software. "cmss17" is a Reserved Font Name for this Font Software. "cmss8" is a Reserved Font Name for this Font Software. "cmss9" is a Reserved Font Name for this Font Software. "cmssbx10" is a Reserved Font Name for this Font Software. "cmssdc10" is a Reserved Font Name for this Font Software. "cmssi10" is a Reserved Font Name for this Font Software. "cmssi12" is a Reserved Font Name for this Font Software. "cmssi17" is a Reserved Font Name for this Font Software. "cmssi8" is a Reserved Font Name for this Font Software. "cmssi9" is a Reserved Font Name for this Font Software. "cmssq8" is a Reserved Font Name for this Font Software. "cmssqi8" is a Reserved Font Name for this Font Software. "cmsy10" is a Reserved Font Name for this Font Software. "cmsy5" is a Reserved Font Name for this Font Software. "cmsy6" is a Reserved Font Name for this Font Software. "cmsy7" is a Reserved Font Name for this Font Software. "cmsy8" is a Reserved Font Name for this Font Software. "cmsy9" is a Reserved Font Name for this Font Software. "cmtcsc10" is a Reserved Font Name for this Font Software. "cmtex10" is a Reserved Font Name for this Font Software. "cmtex8" is a Reserved Font Name for this Font Software. "cmtex9" is a Reserved Font Name for this Font Software. "cmti10" is a Reserved Font Name for this Font Software. "cmti12" is a Reserved Font Name for this Font Software. "cmti7" is a Reserved Font Name for this Font Software. "cmti8" is a Reserved Font Name for this Font Software. "cmti9" is a Reserved Font Name for this Font Software. "cmtt10" is a Reserved Font Name for this Font Software. "cmtt12" is a Reserved Font Name for this Font Software. "cmtt8" is a Reserved Font Name for this Font Software. "cmtt9" is a Reserved Font Name for this Font Software. "cmu10" is a Reserved Font Name for this Font Software. "cmvtt10" is a Reserved Font Name for this Font Software. "euex10" is a Reserved Font Name for this Font Software. "euex7" is a Reserved Font Name for this Font Software. "euex8" is a Reserved Font Name for this Font Software. "euex9" is a Reserved Font Name for this Font Software. "eufb10" is a Reserved Font Name for this Font Software. "eufb5" is a Reserved Font Name for this Font Software. "eufb7" is a Reserved Font Name for this Font Software. "eufm10" is a Reserved Font Name for this Font Software. "eufm5" is a Reserved Font Name for this Font Software. "eufm7" is a Reserved Font Name for this Font Software. "eurb10" is a Reserved Font Name for this Font Software. "eurb5" is a Reserved Font Name for this Font Software. "eurb7" is a Reserved Font Name for this Font Software. "eurm10" is a Reserved Font Name for this Font Software. "eurm5" is a Reserved Font Name for this Font Software. "eurm7" is a Reserved Font Name for this Font Software. "eusb10" is a Reserved Font Name for this Font Software. "eusb5" is a Reserved Font Name for this Font Software. "eusb7" is a Reserved Font Name for this Font Software. "eusm10" is a Reserved Font Name for this Font Software. "eusm5" is a Reserved Font Name for this Font Software. "eusm7" is a Reserved Font Name for this Font Software. "lasy10" is a Reserved Font Name for this Font Software. "lasy5" is a Reserved Font Name for this Font Software. "lasy6" is a Reserved Font Name for this Font Software. "lasy7" is a Reserved Font Name for this Font Software. "lasy8" is a Reserved Font Name for this Font Software. "lasy9" is a Reserved Font Name for this Font Software. "lasyb10" is a Reserved Font Name for this Font Software. "lcircle1" is a Reserved Font Name for this Font Software. "lcirclew" is a Reserved Font Name for this Font Software. "lcmss8" is a Reserved Font Name for this Font Software. "lcmssb8" is a Reserved Font Name for this Font Software. "lcmssi8" is a Reserved Font Name for this Font Software. "line10" is a Reserved Font Name for this Font Software. "linew10" is a Reserved Font Name for this Font Software. "msam10" is a Reserved Font Name for this Font Software. "msam5" is a Reserved Font Name for this Font Software. "msam6" is a Reserved Font Name for this Font Software. "msam7" is a Reserved Font Name for this Font Software. "msam8" is a Reserved Font Name for this Font Software. "msam9" is a Reserved Font Name for this Font Software. "msbm10" is a Reserved Font Name for this Font Software. "msbm5" is a Reserved Font Name for this Font Software. "msbm6" is a Reserved Font Name for this Font Software. "msbm7" is a Reserved Font Name for this Font Software. "msbm8" is a Reserved Font Name for this Font Software. "msbm9" is a Reserved Font Name for this Font Software. "wncyb10" is a Reserved Font Name for this Font Software. "wncyi10" is a Reserved Font Name for this Font Software. "wncyr10" is a Reserved Font Name for this Font Software. "wncysc10" is a Reserved Font Name for this Font Software. "wncyss10" is a Reserved Font Name for this Font Software. This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL ----------------------------------------------------------- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ----------------------------------------------------------- PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. "Reserved Font Name" refers to any names specified as such after the copyright statement(s). "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. Name: BaKoMa Fonts Files: matplotlib/mpl-data/fonts/ttf/cm*.ttf matplotlib/mpl-data/fonts/afm/cm*.afm Description: Computer Modern Fonts in PostScript Type 1 and TrueType font formats. License: BaKoMa Fonts Licence BaKoMa Fonts Licence -------------------- This licence covers two font packs (known as BaKoMa Fonts Collection, which is available at `CTAN:fonts/cm/ps-type1/bakoma/'): 1) BaKoMa-CM (1.1/12-Nov-94) Computer Modern Fonts in PostScript Type 1 and TrueType font formats. 2) BaKoMa-AMS (1.2/19-Jan-95) AMS TeX fonts in PostScript Type 1 and TrueType font formats. Copyright (C) 1994, 1995, Basil K. Malyshev. All Rights Reserved. Permission to copy and distribute these fonts for any purpose is hereby granted without fee, provided that the above copyright notice, author statement and this permission notice appear in all copies of these fonts and related documentation. Permission to modify and distribute modified fonts for any purpose is hereby granted without fee, provided that the copyright notice, author statement, this permission notice and location of original fonts (http://www.ctan.org/tex-archive/fonts/cm/ps-type1/bakoma) appear in all copies of modified fonts and related documentation. Permission to use these fonts (embedding into PostScript, PDF, SVG and printing by using any software) is hereby granted without fee. It is not required to provide any notices about using these fonts. Basil K. Malyshev INSTITUTE FOR HIGH ENERGY PHYSICS IHEP, OMVT Moscow Region 142281 PROTVINO RUSSIA E-Mail: bakoma@mail.ru or malyshev@mail.ihep.ru Name: ColorBrewer Color Schemes Files: lib/matplotlib/_cm.py Description: Color schemes from ColorBrewer License: Apache-2.0 Apache-Style Software License for ColorBrewer software and ColorBrewer Color Schemes Copyright (c) 2002 Cynthia Brewer, Mark Harrower, and The Pennsylvania State University. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Name: Courier 10 Files: matplotlib/tests/Courier10PitchBT-Bold.pfb Description: Courier 10 font, used in tests. License: Bitstream-Charter The Courier10PitchBT-Bold.pfb file is a Type-1 version of Courier 10 Pitch BT Bold by Bitstream, obtained from <https://ctan.org/tex-archive/fonts/courierten>. It is included here as test data only, but the following license applies. (c) Copyright 1989-1992, Bitstream Inc., Cambridge, MA. You are hereby granted permission under all Bitstream propriety rights to use, copy, modify, sublicense, sell, and redistribute the 4 Bitstream Charter (r) Type 1 outline fonts and the 4 Courier Type 1 outline fonts for any purpose and without restriction; provided, that this notice is left intact on all copies of such fonts and that Bitstream's trademark is acknowledged as shown below on all unmodified copies of the 4 Charter Type 1 fonts. BITSTREAM CHARTER is a registered trademark of Bitstream Inc. Name: JSXTools resize observer Files: Description: Minimal polyfill for the ResizeObserver API License: CC0-1.0 # CC0 1.0 Universal ## Statement of Purpose The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an “owner”) of an original work of authorship and/or a database (each, a “Work”). Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works (“Commons”) that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the “Affirmer”), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. 1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights (“Copyright and Related Rights”). Copyright and Related Rights include, but are not limited to, the following: 1. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; 2. moral rights retained by the original author(s) and/or performer(s); 3. publicity and privacy rights pertaining to a person’s image or likeness depicted in a Work; 4. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(i), below; 5. rights protecting the extraction, dissemination, use and reuse of data in a Work; 6. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and 7. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. 2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer’s Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the “Waiver”). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer’s heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer’s express Statement of Purpose. 3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer’s express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer’s Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the “License”). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer’s express Statement of Purpose. 4. Limitations and Disclaimers. 1. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. 2. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. 3. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person’s Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. 4. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. For more information, please see http://creativecommons.org/publicdomain/zero/1.0/. Name: QHull Files: matplotlib/_qhull.*.so Description: Convex hull, Delaunay triangulation, Voronoi diagrams, Halfspace intersection License: Qhull Qhull, Copyright (c) 1993-2020 C.B. Barber Arlington, MA and The National Science and Technology Research Center for Computation and Visualization of Geometric Structures (The Geometry Center) University of Minnesota email: qhull@qhull.org This software includes Qhull from C.B. Barber and The Geometry Center. Files derived from Qhull 1.0 are copyrighted by the Geometry Center. The remaining files are copyrighted by C.B. Barber. Qhull is free software and may be obtained via http from www.qhull.org. It may be freely copied, modified, and redistributed under the following conditions: 1. All copyright notices must remain intact in all files. 2. A copy of this text file must be distributed along with any copies of Qhull that you redistribute; this includes copies that you have modified, or copies of programs or other software products that include Qhull. 3. If you modify Qhull, you must include a notice giving the name of the person performing the modification, the date of modification, and the reason for such modification. 4. When distributing modified versions of Qhull, or other software products that include Qhull, you must provide notice that the original source code may be obtained as noted above. 5. There is no warranty or other guarantee of fitness for Qhull, it is provided solely "as is". Bug reports or fixes may be sent to qhull_bug@qhull.org; the authors may or may not act on them as they desire. Name: Qt4 Editor Files: matplotlib/backends/qt_editor Description: Module creating PyQt4 form dialogs/layouts to edit various type of parameters License: MIT Module creating PyQt4 form dialogs/layouts to edit various type of parameters formlayout License Agreement (MIT License) ------------------------------------------ Copyright (c) 2009 Pierre Raybaut Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ Name: Solarized Files: matplotlib/mpl-data/stylelib/Solarize_Light2.mplstyle Description: Solarized color scheme/style License: MIT https://github.com/altercation/solarized/blob/master/LICENSE Copyright (c) 2011 Ethan Schoonover Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Name: Stix fonts Files: matplotlib/mpl-data/fonts/ttf/STIX*.ttf Description: STIX fonts License: TERMS AND CONDITIONS 1. Permission is hereby granted, free of charge, to any person obtaining a copy of the STIX Fonts-TM set accompanying this license (collectively, the "Fonts") and the associated documentation files (collectively with the Fonts, the "Font Software"), to reproduce and distribute the Font Software, including the rights to use, copy, merge and publish copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so same, subject to the following terms and conditions (the "License"). 2. The following copyright and trademark notice and these Terms and Conditions shall be included in all copies of one or more of the Font typefaces and any derivative work created as permitted under this License: Copyright (c) 2001-2005 by the STI Pub Companies, consisting of the American Institute of Physics, the American Chemical Society, the American Mathematical Society, the American Physical Society, Elsevier, Inc., and The Institute of Electrical and Electronic Engineers, Inc. Portions copyright (c) 1998-2003 by MicroPress, Inc. Portions copyright (c) 1990 by Elsevier, Inc. All rights reserved. STIX Fonts-TM is a trademark of The Institute of Electrical and Electronics Engineers, Inc. 3. You may (a) convert the Fonts from one format to another (e.g., from TrueType to PostScript), in which case the normal and reasonable distortion that occurs during such conversion shall be permitted and (b) embed or include a subset of the Fonts in a document for the purposes of allowing users to read text in the document that utilizes the Fonts. In each case, you may use the STIX Fonts-TM mark to designate the resulting Fonts or subset of the Fonts. 4. You may also (a) add glyphs or characters to the Fonts, or modify the shape of existing glyphs, so long as the base set of glyphs is not removed and (b) delete glyphs or characters from the Fonts, provided that the resulting font set is distributed with the following disclaimer: "This [name] font does not include all the Unicode points covered in the STIX Fonts-TM set but may include others." In each case, the name used to denote the resulting font set shall not include the term "STIX" or any similar term. 5. You may charge a fee in connection with the distribution of the Font Software, provided that no copy of one or more of the individual Font typefaces that form the STIX Fonts-TM set may be sold by itself. 6. THE FONT SOFTWARE IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK OR OTHER RIGHT. IN NO EVENT SHALL MICROPRESS OR ANY OF THE STI PUB COMPANIES BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING, BUT NOT LIMITED TO, ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM OR OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. 7. Except as contained in the notice set forth in Section 2, the names MicroPress Inc. and STI Pub Companies, as well as the names of the companies/organizations that compose the STI Pub Companies, shall not be used in advertising or otherwise to promote the sale, use or other dealings in the Font Software without the prior written consent of the respective company or organization. 8. This License shall become null and void in the event of any material breach of the Terms and Conditions herein by licensee. 9. A substantial portion of the STIX Fonts set was developed by MicroPress Inc. for the STI Pub Companies. To obtain additional mathematical fonts, please contact MicroPress, Inc., 68-30 Harrow Street, Forest Hills, NY 11375, USA - Phone: (718) 575-1816. Name: Yorick Colormaps Files: lib/matplotlib/_cm.py Description: Gist/Yorick colormaps License: BSD-style license for gist/yorick colormaps. Copyright: Copyright (c) 1996. The Regents of the University of California. All rights reserved. Permission to use, copy, modify, and distribute this software for any purpose without fee is hereby granted, provided that this entire notice is included in all copies of any software which is or includes a copy or modification of this software and in all copies of the supporting documentation for such software. This work was produced at the University of California, Lawrence Livermore National Laboratory under contract no. W-7405-ENG-48 between the U.S. Department of Energy and The Regents of the University of California for the operation of UC LLNL. DISCLAIMER This software was prepared as an account of work sponsored by an agency of the United States Government. Neither the United States Government nor the University of California nor any of their employees, makes any warranty, express or implied, or assumes any liability or responsibility for the accuracy, completeness, or usefulness of any information, apparatus, product, or process disclosed, or represents that its use would not infringe privately-owned rights. Reference herein to any specific commercial products, process, or service by trade name, trademark, manufacturer, or otherwise, does not necessarily constitute or imply its endorsement, recommendation, or favoring by the United States Government or the University of California. The views and opinions of authors expressed herein do not necessarily state or reflect those of the United States Government or the University of California, and shall not be used for advertising or product endorsement purposes. AUTHOR David H. Munro wrote Yorick and Gist. Berkeley Yacc (byacc) generated the Yorick parser. The routines in Math are from LAPACK and FFTPACK; MathC contains C translations by David H. Munro. The algorithms for Yorick's random number generator and several special functions in Yorick/include were taken from Numerical Recipes by Press, et. al., although the Yorick implementations are unrelated to those in Numerical Recipes. A small amount of code in Gist was adapted from the X11R4 release, copyright M.I.T. -- the complete copyright notice may be found in the (unused) file Gist/host.c. Classifier: Development Status :: 5 - Production/StableClassifier: Framework :: MatplotlibClassifier: Intended Audience :: Science/ResearchClassifier: Intended Audience :: EducationClassifier: License :: OSI Approved :: Python Software Foundation LicenseClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Topic :: Scientific/Engineering :: VisualizationProject-URL: Homepage, https://matplotlib.orgProject-URL: Download, https://matplotlib.org/stable/install/index.htmlProject-URL: Documentation, https://matplotlib.orgProject-URL: Source Code, https://github.com/matplotlib/matplotlibProject-URL: Bug Tracker, https://github.com/matplotlib/matplotlib/issuesProject-URL: Forum, https://discourse.matplotlib.org/Project-URL: Donate, https://numfocus.org/donate-to-matplotlibRequires-Python: >=3.10Requires-Dist: contourpy>=1.0.1Requires-Dist: cycler>=0.10Requires-Dist: fonttools>=4.22.0Requires-Dist: kiwisolver>=1.3.1Requires-Dist: numpy>=1.23Requires-Dist: packaging>=20.0Requires-Dist: pillow>=8Requires-Dist: pyparsing>=3Requires-Dist: python-dateutil>=2.7Provides-Extra: devRequires-Dist: meson-python<0.17.0,>=0.13.1; extra == "dev"Requires-Dist: pybind11!=2.13.3,>=2.13.2; extra == "dev"Requires-Dist: setuptools_scm<10,>=7; extra == "dev"Requires-Dist: setuptools>=64; extra == "dev"Description-Content-Type: text/markdown
[](https://pypi.org/project/matplotlib/)[](https://anaconda.org/conda-forge/matplotlib)[](https://pypi.org/project/matplotlib)[](https://numfocus.org)
[](https://discourse.matplotlib.org)[](https://gitter.im/matplotlib/matplotlib)[](https://github.com/matplotlib/matplotlib/issues)[](https://matplotlib.org/stable/devel/index.html)
[](https://github.com/matplotlib/matplotlib/actions?query=workflow%3ATests)[](https://dev.azure.com/matplotlib/matplotlib/_build/latest?definitionId=1&branchName=main)[](https://ci.appveyor.com/project/matplotlib/matplotlib)[](https://app.codecov.io/gh/matplotlib/matplotlib)[](https://jacobtomlinson.dev/effver)

Matplotlib is a comprehensive library for creating static, animated, andinteractive visualizations in Python.
Check out our [home page](https://matplotlib.org/) for more information.

Matplotlib produces publication-quality figures in a variety of hardcopyformats and interactive environments across platforms. Matplotlib can beused in Python scripts, Python/IPython shells, web application servers,and various graphical user interface toolkits.
## Install
See the [installdocumentation](https://matplotlib.org/stable/users/installing/index.html),which is generated from `/doc/install/index.rst`
## Contribute
You've discovered a bug or something else you want to change — excellent!
You've worked out a way to fix it — even better!
You want to tell us about it — best of all!
Start at the [contributingguide](https://matplotlib.org/devdocs/devel/contribute.html)!
## Contact
[Discourse](https://discourse.matplotlib.org/) is the discussion forumfor general questions and discussions and our recommended startingpoint.
Our active mailing lists (which are mirrored on Discourse) are:
- [Users](https://mail.python.org/mailman/listinfo/matplotlib-users) mailing list: <matplotlib-users@python.org>- [Announcement](https://mail.python.org/mailman/listinfo/matplotlib-announce) mailing list: <matplotlib-announce@python.org>- [Development](https://mail.python.org/mailman/listinfo/matplotlib-devel) mailing list: <matplotlib-devel@python.org>
[Gitter](https://gitter.im/matplotlib/matplotlib) is for coordinatingdevelopment and asking questions directly related to contributing tomatplotlib.
## Citing Matplotlib
If Matplotlib contributes to a project that leads to publication, pleaseacknowledge this by citing Matplotlib.
[A ready-made citationentry](https://matplotlib.org/stable/users/project/citing.html) isavailable.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086Metadata-Version: 2.1Name: scipyVersion: 1.17.1Summary: Fundamental algorithms for scientific computing in PythonMaintainer-Email: SciPy Developers <scipy-dev@python.org>License: Copyright (c) 2001-2002 Enthought, Inc. 2003, SciPy Developers. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---- This binary distribution of SciPy can also bundle the following software (depending on the build): Name: OpenBLAS Files: scipy.libs/libscipy_openblas*.so Description: bundled as a dynamically linked library Availability: https://github.com/OpenMathLib/OpenBLAS/ License: BSD-3-Clause Copyright (c) 2011-2014, The OpenBLAS Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the OpenBLAS project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Name: LAPACK Files: scipy.libs/libscipy_openblas*.so Description: bundled in OpenBLAS Availability: https://github.com/OpenMathLib/OpenBLAS/ License: BSD-3-Clause-Open-MPI Copyright (c) 1992-2013 The University of Tennessee and The University of Tennessee Research Foundation. All rights reserved. Copyright (c) 2000-2013 The University of California Berkeley. All rights reserved. Copyright (c) 2006-2013 The University of Colorado Denver. All rights reserved. $COPYRIGHT$ Additional copyrights may follow $HEADER$ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer listed in this license in the documentation and/or other materials provided with the distribution. - Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. The copyright holders provide no reassurances that the source code provided does not infringe any patent, copyright, or any other intellectual property rights of third parties. The copyright holders disclaim any liability to any recipient for claims brought against recipient by any third party for infringement of that parties intellectual property rights. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Name: GCC runtime library Files: scipy.libs/libgfortran*.so Description: dynamically linked to files compiled with gcc Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libgfortran License: GPL-3.0-or-later WITH GCC-exception-3.1 Copyright (C) 2002-2017 Free Software Foundation, Inc. Libgfortran is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. Libgfortran is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. ---- Full text of license texts referred to above follows (that they are listed below does not necessarily imply the conditions apply to the present binary release): ---- GCC RUNTIME LIBRARY EXCEPTION Version 3.1, 31 March 2009 Copyright (C) 2009 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This GCC Runtime Library Exception ("Exception") is an additional permission under section 7 of the GNU General Public License, version 3 ("GPLv3"). It applies to a given file (the "Runtime Library") that bears a notice placed by the copyright holder of the file stating that the file is governed by GPLv3 along with this Exception. When you use GCC to compile a program, GCC may combine portions of certain GCC header files and runtime libraries with the compiled program. The purpose of this Exception is to allow compilation of non-GPL (including proprietary) programs to use, in this way, the header files and runtime libraries covered by this Exception. 0. Definitions. A file is an "Independent Module" if it either requires the Runtime Library for execution after a Compilation Process, or makes use of an interface provided by the Runtime Library, but is not otherwise based on the Runtime Library. "GCC" means a version of the GNU Compiler Collection, with or without modifications, governed by version 3 (or a specified later version) of the GNU General Public License (GPL) with the option of using any subsequent versions published by the FSF. "GPL-compatible Software" is software whose conditions of propagation, modification and use would permit combination with GCC in accord with the license of GCC. "Target Code" refers to output from any compiler for a real or virtual target processor architecture, in executable form or suitable for input to an assembler, loader, linker and/or execution phase. Notwithstanding that, Target Code does not include data in any format that is used as a compiler intermediate representation, or used for producing a compiler intermediate representation. The "Compilation Process" transforms code entirely represented in non-intermediate languages designed for human-written code, and/or in Java Virtual Machine byte code, into Target Code. Thus, for example, use of source code generators and preprocessors need not be considered part of the Compilation Process, since the Compilation Process can be understood as starting with the output of the generators or preprocessors. A Compilation Process is "Eligible" if it is done using GCC, alone or with other GPL-compatible software, or if it is done without using any work based on GCC. For example, using non-GPL-compatible Software to optimize any GCC intermediate representations would not qualify as an Eligible Compilation Process. 1. Grant of Additional Permission. You have permission to propagate a work of Target Code formed by combining the Runtime Library with Independent Modules, even if such propagation would otherwise violate the terms of GPLv3, provided that all Target Code was generated by Eligible Compilation Processes. You may then convey such a combination under terms of your choice, consistent with the licensing of the Independent Modules. 2. No Weakening of GCC Copyleft. The availability of this Exception does not imply any general presumption that third-party software is unaffected by the copyleft requirements of the license of GCC. ---- GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. Name: libquadmath Files: scipy.libs/libquadmath*.so Description: dynamically linked to files compiled with gcc Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libquadmath License: LGPL-2.1-or-later GCC Quad-Precision Math Library Copyright (C) 2010-2019 Free Software Foundation, Inc. Written by Francois-Xavier Coudert <fxcoudert@gcc.gnu.org> This file is part of the libquadmath library. Libquadmath is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Libquadmath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html Classifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: Science/ResearchClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: BSD LicenseClassifier: Programming Language :: CClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Topic :: Software Development :: LibrariesClassifier: Topic :: Scientific/EngineeringClassifier: Operating System :: Microsoft :: WindowsClassifier: Operating System :: POSIX :: LinuxClassifier: Operating System :: POSIXClassifier: Operating System :: UnixClassifier: Operating System :: MacOSProject-URL: homepage, https://scipy.org/Project-URL: documentation, https://docs.scipy.org/doc/scipy/Project-URL: source, https://github.com/scipy/scipyProject-URL: download, https://github.com/scipy/scipy/releasesProject-URL: tracker, https://github.com/scipy/scipy/issuesRequires-Python: >=3.11Requires-Dist: numpy<2.7,>=1.26.4Provides-Extra: testRequires-Dist: pytest>=8.0.0; extra == "test"Requires-Dist: pytest-cov; extra == "test"Requires-Dist: pytest-timeout; extra == "test"Requires-Dist: pytest-xdist; extra == "test"Requires-Dist: asv; extra == "test"Requires-Dist: mpmath; extra == "test"Requires-Dist: gmpy2; extra == "test"Requires-Dist: threadpoolctl; extra == "test"Requires-Dist: scikit-umfpack; extra == "test"Requires-Dist: pooch; extra == "test"Requires-Dist: hypothesis>=6.30; extra == "test"Requires-Dist: array-api-strict>=2.3.1; extra == "test"Requires-Dist: Cython; extra == "test"Requires-Dist: meson; extra == "test"Requires-Dist: ninja; sys_platform != "emscripten" and extra == "test"Provides-Extra: docRequires-Dist: sphinx<8.2.0,>=5.0.0; extra == "doc"Requires-Dist: intersphinx_registry; extra == "doc"Requires-Dist: pydata-sphinx-theme>=0.15.2; extra == "doc"Requires-Dist: sphinx-copybutton; extra == "doc"Requires-Dist: sphinx-design>=0.4.0; extra == "doc"Requires-Dist: matplotlib>=3.5; extra == "doc"Requires-Dist: numpydoc; extra == "doc"Requires-Dist: jupytext; extra == "doc"Requires-Dist: myst-nb>=1.2.0; extra == "doc"Requires-Dist: pooch; extra == "doc"Requires-Dist: jupyterlite-sphinx>=0.19.1; extra == "doc"Requires-Dist: jupyterlite-pyodide-kernel; extra == "doc"Requires-Dist: linkify-it-py; extra == "doc"Requires-Dist: tabulate; extra == "doc"Provides-Extra: devRequires-Dist: click<8.3.0; extra == "dev"Requires-Dist: spin; extra == "dev"Requires-Dist: mypy==1.10.0; extra == "dev"Requires-Dist: typing_extensions; extra == "dev"Requires-Dist: types-psutil; extra == "dev"Requires-Dist: pycodestyle; extra == "dev"Requires-Dist: ruff>=0.12.0; extra == "dev"Requires-Dist: cython-lint>=0.12.2; extra == "dev"Description-Content-Type: text/x-rst
.. image:: https://raw.githubusercontent.com/scipy/scipy/main/doc/source/_static/logo.svg :target: https://scipy.org :width: 110 :height: 110 :align: left
.. image:: https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A :target: https://numfocus.org
.. image:: https://img.shields.io/pypi/dm/scipy.svg?label=Pypi%20downloads :target: https://pypi.org/project/scipy/
.. image:: https://img.shields.io/conda/dn/conda-forge/scipy.svg?label=Conda%20downloads :target: https://anaconda.org/conda-forge/scipy
.. image:: https://img.shields.io/badge/stackoverflow-Ask%20questions-blue.svg :target: https://stackoverflow.com/questions/tagged/scipy
.. image:: https://img.shields.io/badge/DOI-10.1038%2Fs41592--019--0686--2-blue.svg :target: https://www.nature.com/articles/s41592-019-0686-2
.. image:: https://insights.linuxfoundation.org/api/badge/health-score?project=scipy :target: https://insights.linuxfoundation.org/project/scipy
SciPy (pronounced "Sigh Pie") is an open-source software for mathematics,science, and engineering. It includes modules for statistics, optimization,integration, linear algebra, Fourier transforms, signal and image processing,ODE solvers, and more.
- **Website:** https://scipy.org- **Documentation:** https://docs.scipy.org/doc/scipy/- **Development version of the documentation:** https://scipy.github.io/devdocs- **SciPy development forum:** https://discuss.scientific-python.org/c/contributor/scipy- **Stack Overflow:** https://stackoverflow.com/questions/tagged/scipy- **Source code:** https://github.com/scipy/scipy- **Contributing:** https://scipy.github.io/devdocs/dev/index.html- **Bug reports:** https://github.com/scipy/scipy/issues- **Code of Conduct:** https://docs.scipy.org/doc/scipy/dev/conduct/code_of_conduct.html- **Report a security vulnerability:** https://tidelift.com/docs/security- **Citing in your work:** https://www.scipy.org/citing-scipy/
SciPy is built to work withNumPy arrays, and provides many user-friendly and efficient numerical routines,such as routines for numerical integration and optimization. Together, theyrun on all popular operating systems, are quick to install, and are free ofcharge. NumPy and SciPy are easy to use, but powerful enough to be dependedupon by some of the world's leading scientists and engineers. If you need tomanipulate numbers on a computer and display or publish the results, giveSciPy a try!
For the installation instructions, see `our installguide <https://scipy.org/install/>`__.
Call for Contributions----------------------
We appreciate and welcome contributions. Small improvements or fixes are always appreciated; issues labeled as "goodfirst issue" may be a good starting point. Have a look at `our contributingguide <https://scipy.github.io/devdocs/dev/index.html>`__.
Writing code isn’t the only way to contribute to SciPy. You can also:
- review pull requests- triage issues- develop tutorials, presentations, and other educational materials- maintain and improve `our website <https://github.com/scipy/scipy.org>`__- develop graphic design for our brand assets and promotional materials- help with outreach and onboard new contributors- write grant proposals and help with other fundraising efforts
If you’re unsure where to start or how your skills fit in, reach out! You canask on the `forum <https://discuss.scientific-python.org/c/contributor/scipy>`__or here, on GitHub, by leaving a comment on a relevant issue that is alreadyopen.
If you are new to contributing to open source, `thisguide <https://opensource.guide/how-to-contribute/>`__ helps explain why, what,and how to get involved.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300Metadata-Version: 2.4Name: segmentation_models_pytorchVersion: 0.5.0Summary: Image segmentation models with pre-trained backbones. PyTorch.Author-email: Pavel Iakubovskii <qubvel@gmail.com>License: The MIT License Copyright (c) 2019, Pavel Iakubovskii Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Project-URL: Homepage, https://github.com/qubvel-org/segmentation_models.pytorchClassifier: License :: OSI Approved :: MIT LicenseClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyRequires-Python: >=3.9Description-Content-Type: text/markdownLicense-File: LICENSERequires-Dist: huggingface-hub>=0.24Requires-Dist: numpy>=1.19.3Requires-Dist: pillow>=8Requires-Dist: safetensors>=0.3.1Requires-Dist: timm>=0.9Requires-Dist: torch>=1.8Requires-Dist: torchvision>=0.9Requires-Dist: tqdm>=4.42.1Provides-Extra: docsRequires-Dist: autodocsumm; extra == "docs"Requires-Dist: huggingface-hub; extra == "docs"Requires-Dist: six; extra == "docs"Requires-Dist: sphinx; extra == "docs"Requires-Dist: sphinx-book-theme; extra == "docs"Provides-Extra: testRequires-Dist: gitpython; extra == "test"Requires-Dist: packaging; extra == "test"Requires-Dist: pytest; extra == "test"Requires-Dist: pytest-cov; extra == "test"Requires-Dist: pytest-xdist; extra == "test"Requires-Dist: ruff>=0.9; extra == "test"Requires-Dist: setuptools; extra == "test"Dynamic: license-file
<div align="center">  **Python library with Neural Networks for Image Semantic Segmentation based on [PyTorch](https://pytorch.org/).**
[](https://github.com/qubvel/segmentation_models.pytorch/actions/workflows/tests.yml) [](https://smp.readthedocs.io/en/latest/) <br>[](https://pypi.org/project/segmentation-models-pytorch/) [](https://pepy.tech/project/segmentation-models-pytorch) [](https://pepy.tech/project/segmentation-models-pytorch) <br>[](https://github.com/qubvel/segmentation_models.pytorch/blob/main/LICENSE)[](https://pepy.tech/project/segmentation-models-pytorch)
</div>
The main features of the library are:
- Super simple high-level API (just two lines to create a neural network) - 12 encoder-decoder model architectures (Unet, Unet++, Segformer, DPT, ...) - 800+ **pretrained** convolution- and transform-based encoders, including [timm](https://github.com/huggingface/pytorch-image-models) support - Popular metrics and losses for training routines (Dice, Jaccard, Tversky, ...) - ONNX export and torch script/trace/compile friendly
### Community-Driven Project, Supported By<table> <tr> <td align="center" vertical-align="center"> <a href="https://withoutbg.com/?utm_source=smp&utm_medium=github_readme&utm_campaign=sponsorship" > <img src="https://withoutbg.com/images/logo-social.png" width="70px;" alt="withoutBG API Logo" /> </a> </td> <td align="center" vertical-align="center"> <b>withoutBG API</b> <br /> <a href="https://withoutbg.com/?utm_source=smp&utm_medium=github_readme&utm_campaign=sponsorship">https://withoutbg.com</a> <br /> <p width="200px"> High-quality background removal API <br/> </p> </td> </tr></table> ### [📚 Project Documentation 📚](http://smp.readthedocs.io/)
Visit [Read The Docs Project Page](https://smp.readthedocs.io/) or read the following README to know more about Segmentation Models Pytorch (SMP for short) library
### 📋 Table of content 1. [Quick start](#start) 2. [Examples](#examples) 3. [Models and encoders](#models-and-encoders) 4. [Models API](#api) 1. [Input channels](#input-channels) 2. [Auxiliary classification output](#auxiliary-classification-output) 3. [Depth](#depth) 5. [Installation](#installation) 6. [Competitions won with the library](#competitions) 7. [Contributing](#contributing) 8. [Citing](#citing) 9. [License](#license)
## ⏳ Quick start <a name="start"></a>
#### 1. Create your first Segmentation model with SMP
The segmentation model is just a PyTorch `torch.nn.Module`, which can be created as easy as:
```pythonimport segmentation_models_pytorch as smp
model = smp.Unet( encoder_name="resnet34", # choose encoder, e.g. mobilenet_v2 or efficientnet-b7 encoder_weights="imagenet", # use `imagenet` pre-trained weights for encoder initialization in_channels=1, # model input channels (1 for gray-scale images, 3 for RGB, etc.) classes=3, # model output channels (number of classes in your dataset))``` - see [table](#architectures) with available model architectures - see [table](#encoders) with available encoders and their corresponding weights
#### 2. Configure data preprocessing
All encoders have pretrained weights. Preparing your data the same way as during weights pre-training may give you better results (higher metric score and faster convergence). It is **not necessary** in case you train the whole model, not only the decoder.
```pythonfrom segmentation_models_pytorch.encoders import get_preprocessing_fn
preprocess_input = get_preprocessing_fn('resnet18', pretrained='imagenet')```
Congratulations! You are done! Now you can train your model with your favorite framework!
## 💡 Examples <a name="examples"></a>
| Name | Link | Colab ||-------------------------------------------|-----------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------|| **Train** pets binary segmentation on OxfordPets | [Notebook](https://github.com/qubvel/segmentation_models.pytorch/blob/main/examples/binary_segmentation_intro.ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/binary_segmentation_intro.ipynb) || **Train** cars binary segmentation on CamVid | [Notebook](https://github.com/qubvel/segmentation_models.pytorch/blob/main/examples/cars%20segmentation%20(camvid).ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/cars%20segmentation%20(camvid).ipynb) || **Train** multiclass segmentation on CamVid | [Notebook](https://github.com/qubvel-org/segmentation_models.pytorch/blob/main/examples/camvid_segmentation_multiclass.ipynb) | [](https://colab.research.google.com/github/qubvel-org/segmentation_models.pytorch/blob/main/examples/camvid_segmentation_multiclass.ipynb) || **Train** clothes binary segmentation by @ternaus | [Repo](https://github.com/ternaus/cloths_segmentation) | || **Load and inference** pretrained Segformer | [Notebook](https://github.com/qubvel-org/segmentation_models.pytorch/blob/main/examples/segformer_inference_pretrained.ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/segformer_inference_pretrained.ipynb) || **Load and inference** pretrained DPT | [Notebook](https://github.com/qubvel-org/segmentation_models.pytorch/blob/main/examples/dpt_inference_pretrained.ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/dpt_inference_pretrained.ipynb) || **Load and inference** pretrained DPT | [Notebook](https://github.com/qubvel-org/segmentation_models.pytorch/blob/main/examples/upernet_inference_pretrained.ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/upernet_inference_pretrained.ipynb) || **Save and load** models locally / to HuggingFace Hub |[Notebook](https://github.com/qubvel-org/segmentation_models.pytorch/blob/main/examples/save_load_model_and_share_with_hf_hub.ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/save_load_model_and_share_with_hf_hub.ipynb)| **Export** trained model to ONNX | [Notebook](https://github.com/qubvel/segmentation_models.pytorch/blob/main/examples/convert_to_onnx.ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/convert_to_onnx.ipynb) |
## 📦 Models and encoders <a name="models-and-encoders"></a>
### Architectures <a name="architectures"></a>| Architecture | Paper | Documentation | Checkpoints ||--------------|-------|---------------|------------|| Unet | [paper](https://arxiv.org/abs/1505.04597) | [docs](https://smp.readthedocs.io/en/latest/models.html#unet) | || Unet++ | [paper](https://arxiv.org/pdf/1807.10165.pdf) | [docs](https://smp.readthedocs.io/en/latest/models.html#unetplusplus) | || MAnet | [paper](https://ieeexplore.ieee.org/abstract/document/9201310) | [docs](https://smp.readthedocs.io/en/latest/models.html#manet) | || Linknet | [paper](https://arxiv.org/abs/1707.03718) | [docs](https://smp.readthedocs.io/en/latest/models.html#linknet) | || FPN | [paper](http://presentations.cocodataset.org/COCO17-Stuff-FAIR.pdf) | [docs](https://smp.readthedocs.io/en/latest/models.html#fpn) | || PSPNet | [paper](https://arxiv.org/abs/1612.01105) | [docs](https://smp.readthedocs.io/en/latest/models.html#pspnet) | || PAN | [paper](https://arxiv.org/abs/1805.10180) | [docs](https://smp.readthedocs.io/en/latest/models.html#pan) | || DeepLabV3 | [paper](https://arxiv.org/abs/1706.05587) | [docs](https://smp.readthedocs.io/en/latest/models.html#deeplabv3) | || DeepLabV3+ | [paper](https://arxiv.org/abs/1802.02611) | [docs](https://smp.readthedocs.io/en/latest/models.html#deeplabv3plus) | || UPerNet | [paper](https://arxiv.org/abs/1807.10221) | [docs](https://smp.readthedocs.io/en/latest/models.html#upernet) | [checkpoints](https://huggingface.co/collections/smp-hub/upernet-67fadcdbe08418c6ea94f768) || Segformer | [paper](https://arxiv.org/abs/2105.15203) | [docs](https://smp.readthedocs.io/en/latest/models.html#segformer) | [checkpoints](https://huggingface.co/collections/smp-hub/segformer-6749eb4923dea2c355f29a1f) || DPT | [paper](https://arxiv.org/abs/2103.13413) | [docs](https://smp.readthedocs.io/en/latest/models.html#dpt) | [checkpoints](https://huggingface.co/collections/smp-hub/dpt-67f30487327c0599a0c62d68) |
### Encoders <a name="encoders"></a>
The library provides a wide range of **pretrained** encoders (also known as backbones) for segmentation models. Instead of using features from the final layer of a classification model, we extract **intermediate features** and feed them into the decoder for segmentation tasks.
All encoders come with **pretrained weights**, which help achieve **faster and more stable convergence** when training segmentation models.
Given the extensive selection of supported encoders, you can choose the best one for your specific use case, for example: - **Lightweight encoders** for low-latency applications or real-time inference on edge devices (mobilenet/mobileone). - **High-capacity architectures** for complex tasks involving a large number of segmented classes, providing superior accuracy (convnext/swin/mit).
By selecting the right encoder, you can balance **efficiency, performance, and model complexity** to suit your project needs.
All encoders and corresponding pretrained weight are listed in the documentation: - [table](https://smp.readthedocs.io/en/latest/encoders.html) with natively ported encoders - [table](https://smp.readthedocs.io/en/latest/encoders_timm.html) with [timm](https://github.com/huggingface/pytorch-image-models) encoders supported
## 🔁 Models API <a name="api"></a>
### Input channels
The input channels parameter allows you to create a model that can process a tensor with an arbitrary number of channels. If you use pretrained weights from ImageNet, the weights of the first convolution will be reused: - For the 1-channel case, it would be a sum of the weights of the first convolution layer. - Otherwise, channels would be populated with weights like `new_weight[:, i] = pretrained_weight[:, i % 3]`, and then scaled with `new_weight * 3 / new_in_channels`.
```pythonmodel = smp.FPN('resnet34', in_channels=1)mask = model(torch.ones([1, 1, 64, 64]))```
### Auxiliary classification output
All models support `aux_params` parameters, which is default set to `None`. If `aux_params = None` then classification auxiliary output is not created, elsemodel produce not only `mask`, but also `label` output with shape `NC`.Classification head consists of GlobalPooling->Dropout(optional)->Linear->Activation(optional) layers, which can be configured by `aux_params` as follows:```pythonaux_params=dict( pooling='avg', # one of 'avg', 'max' dropout=0.5, # dropout ratio, default is None activation='sigmoid', # activation function, default is None classes=4, # define number of output labels)model = smp.Unet('resnet34', classes=4, aux_params=aux_params)mask, label = model(x)```
### Depth
Depth parameter specify a number of downsampling operations in encoder, so you can makeyour model lighter if specify smaller `depth`.```pythonmodel = smp.Unet('resnet34', encoder_depth=4)```
## 🛠 Installation <a name="installation"></a>PyPI version:
```bash$ pip install segmentation-models-pytorch````
The latest version from GitHub:
```bash$ pip install git+https://github.com/qubvel/segmentation_models.pytorch````
## 🏆 Competitions won with the library <a name="competitions"></a>
`Segmentation Models` package is widely used in image segmentation competitions.[Here](https://github.com/qubvel/segmentation_models.pytorch/blob/main/HALLOFFAME.md) you can find competitions, names of the winners and links to their solutions.
## 🤝 Contributing <a name="contributing"></a>
1. Install SMP in dev mode
```bashmake install_dev # Create .venv, install SMP in dev mode```
2. Run tests and code checks
```bashmake test # Run tests suite with pytestmake fixup # Ruff for formatting and lint checks```
3. Update a table (in case you added an encoder)
```bashmake table # Generates a table with encoders and print to stdout```
## 📝 Citing <a name="citing"></a>```@misc{Iakubovskii:2019, Author = {Pavel Iakubovskii}, Title = {Segmentation Models Pytorch}, Year = {2019}, Publisher = {GitHub}, Journal = {GitHub repository}, Howpublished = {\url{https://github.com/qubvel/segmentation_models.pytorch}}}```
## 🛡️ License <a name="license"></a>The project is primarily distributed under [MIT License](https://github.com/qubvel/segmentation_models.pytorch/blob/main/LICENSE), while some files are subject to other licenses. Please refer to [LICENSES](licenses/LICENSES.md) and license statements in each file for careful check, especially for commercial use.1234567891011121314151617181920212223242526272829303132333435363738Metadata-Version: 2.4Name: filelockVersion: 3.29.0Summary: A platform independent file lock.Project-URL: Documentation, https://py-filelock.readthedocs.ioProject-URL: Homepage, https://github.com/tox-dev/py-filelockProject-URL: Source, https://github.com/tox-dev/py-filelockProject-URL: Tracker, https://github.com/tox-dev/py-filelock/issuesMaintainer-email: Bernát Gábor <gaborjbernat@gmail.com>License-Expression: MITLicense-File: LICENSEKeywords: application,cache,directory,log,userClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: MIT LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Topic :: InternetClassifier: Topic :: Software Development :: LibrariesClassifier: Topic :: SystemRequires-Python: >=3.10Description-Content-Type: text/markdown
# filelock
[](https://pypi.org/project/filelock/)[](https://pypi.org/project/filelock/)[](https://py-filelock.readthedocs.io/en/latest/?badge=latest)[](https://pepy.tech/project/filelock)[](https://github.com/tox-dev/py-filelock/actions/workflows/check.yaml)
For more information checkout the [official documentation](https://py-filelock.readthedocs.io/en/latest/index.html).12345678910111213141516171819filelock/__init__.py,sha256=Ig_QNvsAVtctz2-fkq9EUCgXmW6M5PDudiOC85szmis,2612filelock/_api.py,sha256=UxKGuyzWqzb0Bji8_Czq75TVcQWIH1NTNhEHUxyx2js,21347filelock/_async_read_write.py,sha256=C_cRi4sZ7_CWcqdEf0pcA5sdJ2m3EI_2tAW6kS_5P6I,7759filelock/_error.py,sha256=mnelOh0EVyVeskG3rksL4kW3OArL4TMb2-PwmzQWIFg,788filelock/_read_write.py,sha256=5tVPm1TDXvAu0sgva_LQJ4DH-SDo0rVxuYAFLEQGZw4,15323filelock/_soft.py,sha256=t2Q3ikXjI5eVvNqNwntXH1i_Tm84_M9XSRBbtUOCrBc,7833filelock/_unix.py,sha256=pbTsIi29Qv8zBtLsXqc3PzlS3wz2db53M1MIqVo9790,4579filelock/_util.py,sha256=wPf-LvzmdHWHw4DinDeVJlB0GNVOYGNUeNKSnHBQuUU,1716filelock/_windows.py,sha256=kJFOenaffOP6Qza2b3-yxgiPiDcyroWnzz9STGkCrgM,3943filelock/asyncio.py,sha256=Hvcow3feO_EPvo24a_bgbsBoHkNeIiIqipUWoHrCWKk,14556filelock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0filelock/version.py,sha256=yPxgPkfVUcMLHpiiTghdwfldZS0DIKnGryve3QX7bOs,522filelock/_soft_rw/__init__.py,sha256=_ktpGmVObzrvL0K1_EAV3LF7B9JarYxW-mx_eyGPhT0,370filelock/_soft_rw/_async.py,sha256=3MdgJN0SBM-9-Msslt4HeikJtz2cc1tbeN1sWK9NV60,8704filelock/_soft_rw/_sync.py,sha256=gBbGRLEEI42hh17uFGFB654HyAhkqJ0NJ4XFlvTX0Ac,34936filelock-3.29.0.dist-info/METADATA,sha256=ITNdGUDKAIMOF1lOgentezkyEbHgPto8QRo1B79Z9Lc,1977filelock-3.29.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87filelock-3.29.0.dist-info/licenses/LICENSE,sha256=YIyJ1QYK6ZIa3M8yNmlbxlSplG4SMj72wCHfoE4pTUg,1088filelock-3.29.0.dist-info/RECORD,,1234Wheel-Version: 1.0Generator: hatchling 1.29.0Root-Is-Purelib: trueTag: py3-none-any123456789101112131415161718192021MIT License
Copyright (c) 2025 Bernát Gábor and contributors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""A platform independent file lock that supports the with-statement.
.. autodata:: filelock.__version__ :no-value:
"""
from __future__ import annotations
import sysimport warningsfrom typing import TYPE_CHECKING
from ._api import AcquireReturnProxy, BaseFileLockfrom ._error import Timeout
if TYPE_CHECKING: from ._async_read_write import ( AsyncAcquireReadWriteReturnProxy, AsyncReadWriteLock, ) from ._read_write import ReadWriteLockelse: try: from ._async_read_write import AsyncAcquireReadWriteReturnProxy, AsyncReadWriteLock from ._read_write import ReadWriteLock except ImportError: # sqlite3 may be unavailable if Python was built without it or the C library is missing AsyncAcquireReadWriteReturnProxy = None AsyncReadWriteLock = None ReadWriteLock = None
from ._soft import SoftFileLockfrom ._soft_rw import AsyncAcquireSoftReadWriteReturnProxy, AsyncSoftReadWriteLock, SoftReadWriteLockfrom ._unix import UnixFileLock, has_fcntlfrom ._windows import WindowsFileLockfrom .asyncio import ( AsyncAcquireReturnProxy, AsyncSoftFileLock, AsyncUnixFileLock, AsyncWindowsFileLock, BaseAsyncFileLock,)from .version import version
#: version of the project as a string__version__: str = version
if sys.platform == "win32": # pragma: win32 cover _FileLock: type[BaseFileLock] = WindowsFileLock _AsyncFileLock: type[BaseAsyncFileLock] = AsyncWindowsFileLockelse: # pragma: win32 no cover # noqa: PLR5501 if has_fcntl: _FileLock: type[BaseFileLock] = UnixFileLock _AsyncFileLock: type[BaseAsyncFileLock] = AsyncUnixFileLock else: _FileLock = SoftFileLock _AsyncFileLock = AsyncSoftFileLock if warnings is not None: warnings.warn("only soft file lock is available", stacklevel=2)
if TYPE_CHECKING: FileLock = SoftFileLock AsyncFileLock = AsyncSoftFileLockelse: #: Alias for the lock, which should be used for the current platform. FileLock = _FileLock AsyncFileLock = _AsyncFileLock
__all__ = [ "AcquireReturnProxy", "AsyncAcquireReadWriteReturnProxy", "AsyncAcquireReturnProxy", "AsyncAcquireSoftReadWriteReturnProxy", "AsyncFileLock", "AsyncReadWriteLock", "AsyncSoftFileLock", "AsyncSoftReadWriteLock", "AsyncUnixFileLock", "AsyncWindowsFileLock", "BaseAsyncFileLock", "BaseFileLock", "FileLock", "ReadWriteLock", "SoftFileLock", "SoftReadWriteLock", "Timeout", "UnixFileLock", "WindowsFileLock", "__version__",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582from __future__ import annotations
import contextlibimport inspectimport loggingimport osimport pathlibimport sysimport timeimport warningsfrom abc import ABCMeta, abstractmethodfrom dataclasses import dataclassfrom threading import localfrom typing import TYPE_CHECKING, Any, TypeVarfrom weakref import WeakValueDictionary
from ._error import Timeout
#: Sentinel indicating that no explicit file permission mode was passed.#: When used, lock files are created with 0o666 (letting umask and default ACLs control the final permissions)#: and fchmod is skipped so that POSIX default ACL inheritance is preserved._UNSET_FILE_MODE: int = -1
if TYPE_CHECKING: from collections.abc import Callable from types import TracebackType
from ._read_write import ReadWriteLock from ._soft_rw import SoftReadWriteLock
if sys.version_info >= (3, 11): # pragma: no cover (py311+) from typing import Self else: # pragma: no cover (<py311) from typing_extensions import Self
_LOGGER = logging.getLogger("filelock")
# On Windows os.path.realpath calls CreateFileW with share_mode=0, which blocks concurrent DeleteFileW and causes# livelocks under threaded contention with SoftFileLock. os.path.abspath is purely string-based and avoids this._canonical = os.path.abspath if sys.platform == "win32" else os.path.realpath
class _ThreadLocalRegistry(local): def __init__(self) -> None: super().__init__() self.held: dict[str, int] = {}
_registry = _ThreadLocalRegistry()
# This is a helper class which is returned by :meth:`BaseFileLock.acquire` and wraps the lock to make sure __enter__# is not called twice when entering the with statement. If we would simply return *self*, the lock would be acquired# again in the *__enter__* method of the BaseFileLock, but not released again automatically. issue #37 (memory leak)class AcquireReturnProxy: """A context-aware object that will release the lock file when exiting."""
def __init__(self, lock: BaseFileLock | ReadWriteLock | SoftReadWriteLock) -> None: self.lock: BaseFileLock | ReadWriteLock | SoftReadWriteLock = lock
def __enter__(self) -> BaseFileLock | ReadWriteLock | SoftReadWriteLock: return self.lock
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: self.lock.release()
@dataclassclass FileLockContext: """A dataclass which holds the context for a ``BaseFileLock`` object."""
# The context is held in a separate class to allow optional use of thread local storage via the # ThreadLocalFileContext class.
#: The path to the lock file. lock_file: str
#: The default timeout value. timeout: float
#: The mode for the lock files mode: int
#: Whether the lock should be blocking or not blocking: bool
#: The default polling interval value. poll_interval: float
#: The lock lifetime in seconds; ``None`` means the lock never expires. lifetime: float | None = None
#: The file descriptor for the *_lock_file* as it is returned by the os.open() function, not None when lock held lock_file_fd: int | None = None
#: The lock counter is used for implementing the nested locking mechanism. lock_counter: int = 0 # When the lock is acquired is increased and the lock is only released, when this value is 0
class ThreadLocalFileContext(FileLockContext, local): """A thread local version of the ``FileLockContext`` class."""
_T = TypeVar("_T", bound="BaseFileLock")
class FileLockMeta(ABCMeta): _instances: WeakValueDictionary[str, BaseFileLock]
def __call__( # noqa: PLR0913 cls: type[_T], lock_file: str | os.PathLike[str], timeout: float = -1, mode: int = _UNSET_FILE_MODE, thread_local: bool = True, # noqa: FBT001, FBT002 *, blocking: bool = True, is_singleton: bool = False, poll_interval: float = 0.05, lifetime: float | None = None, **kwargs: Any, # capture remaining kwargs for subclasses # noqa: ANN401 ) -> _T: if is_singleton: instance = cls._instances.get(str(lock_file)) if instance: params_to_check = { "thread_local": (thread_local, instance.is_thread_local()), "timeout": (timeout, instance.timeout), "mode": (mode, instance._context.mode), # noqa: SLF001 "blocking": (blocking, instance.blocking), "poll_interval": (poll_interval, instance.poll_interval), "lifetime": (lifetime, instance.lifetime), }
non_matching_params = { name: (passed_param, set_param) for name, (passed_param, set_param) in params_to_check.items() if passed_param != set_param } if not non_matching_params: return instance # ty: ignore[invalid-return-type] # https://github.com/astral-sh/ty/issues/3231
# parameters do not match; raise error msg = "Singleton lock instances cannot be initialized with differing arguments" msg += "\nNon-matching arguments: " for param_name, (passed_param, set_param) in non_matching_params.items(): msg += f"\n\t{param_name} (existing lock has {set_param} but {passed_param} was passed)" raise ValueError(msg)
# Workaround to make `__init__`'s params optional in subclasses # E.g. virtualenv changes the signature of the `__init__` method in the `BaseFileLock` class descendant # (https://github.com/tox-dev/filelock/pull/340)
all_params = { "timeout": timeout, "mode": mode, "thread_local": thread_local, "blocking": blocking, "is_singleton": is_singleton, "poll_interval": poll_interval, "lifetime": lifetime, **kwargs, }
present_params = inspect.signature(cls.__init__).parameters init_params = {key: value for key, value in all_params.items() if key in present_params}
instance = super().__call__(lock_file, **init_params)
if is_singleton: cls._instances[str(lock_file)] = instance
return instance
class BaseFileLock(contextlib.ContextDecorator, metaclass=FileLockMeta): """ Abstract base class for a file lock object.
Provides a reentrant, cross-process exclusive lock backed by OS-level primitives. Subclasses implement the actual locking mechanism (:class:`UnixFileLock <filelock.UnixFileLock>`, :class:`WindowsFileLock <filelock.WindowsFileLock>`, :class:`SoftFileLock <filelock.SoftFileLock>`).
"""
_instances: WeakValueDictionary[str, BaseFileLock]
def __init_subclass__(cls, **kwargs: dict[str, Any]) -> None: """Setup unique state for lock subclasses.""" super().__init_subclass__(**kwargs) cls._instances = WeakValueDictionary()
def __init__( # noqa: PLR0913 self, lock_file: str | os.PathLike[str], timeout: float = -1, mode: int = _UNSET_FILE_MODE, thread_local: bool = True, # noqa: FBT001, FBT002 *, blocking: bool = True, is_singleton: bool = False, poll_interval: float = 0.05, lifetime: float | None = None, ) -> None: """ Create a new lock object.
:param lock_file: path to the file :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in the acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it to a negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock. :param mode: file permissions for the lockfile. When not specified, the OS controls permissions via umask and default ACLs, preserving POSIX default ACL inheritance in shared directories. :param thread_local: Whether this object's internal context should be thread local or not. If this is set to ``False`` then the lock will be reentrant across threads. :param blocking: whether the lock should be blocking or not :param is_singleton: If this is set to ``True`` then only one instance of this class will be created per lock file. This is useful if you want to use the lock object for reentrant locking without needing to pass the same object around. :param poll_interval: default interval for polling the lock file, in seconds. It will be used as fallback value in the acquire method, if no poll_interval value (``None``) is given. :param lifetime: maximum time in seconds a lock can be held before it is considered expired. When set, a waiting process will break a lock whose file modification time is older than ``lifetime`` seconds. ``None`` (the default) means locks never expire.
""" self._is_thread_local = thread_local self._is_singleton = is_singleton
# Create the context. Note that external code should not work with the context directly and should instead use # properties of this class. kwargs: dict[str, Any] = { "lock_file": os.fspath(lock_file), "timeout": timeout, "mode": mode, "blocking": blocking, "poll_interval": poll_interval, "lifetime": lifetime, } self._context: FileLockContext = (ThreadLocalFileContext if thread_local else FileLockContext)(**kwargs)
def is_thread_local(self) -> bool: """:returns: a flag indicating if this lock is thread local or not""" return self._is_thread_local
@property def is_singleton(self) -> bool: """ :returns: a flag indicating if this lock is singleton or not
.. versionadded:: 3.13.0
""" return self._is_singleton
@property def lock_file(self) -> str: """:returns: path to the lock file""" return self._context.lock_file
@property def timeout(self) -> float: """ :returns: the default timeout value, in seconds
.. versionadded:: 2.0.0
""" return self._context.timeout
@timeout.setter def timeout(self, value: float | str) -> None: """ Change the default timeout value.
:param value: the new value, in seconds
""" self._context.timeout = float(value)
@property def blocking(self) -> bool: """ :returns: whether the locking is blocking or not
.. versionadded:: 3.14.0
""" return self._context.blocking
@blocking.setter def blocking(self, value: bool) -> None: """ Change the default blocking value.
:param value: the new value as bool
""" self._context.blocking = value
@property def poll_interval(self) -> float: """ :returns: the default polling interval, in seconds
.. versionadded:: 3.24.0
""" return self._context.poll_interval
@poll_interval.setter def poll_interval(self, value: float) -> None: """ Change the default polling interval.
:param value: the new value, in seconds
""" self._context.poll_interval = value
@property def lifetime(self) -> float | None: """ :returns: the lock lifetime in seconds, or ``None`` if the lock never expires
.. versionadded:: 3.24.0
""" return self._context.lifetime
@lifetime.setter def lifetime(self, value: float | None) -> None: """ Change the lock lifetime.
:param value: the new value in seconds, or ``None`` to disable expiration
""" self._context.lifetime = value
@property def mode(self) -> int: """:returns: the file permissions for the lockfile""" return 0o644 if self._context.mode == _UNSET_FILE_MODE else self._context.mode
@property def has_explicit_mode(self) -> bool: """:returns: whether the file permissions were explicitly set""" return self._context.mode != _UNSET_FILE_MODE
def _open_mode(self) -> int: """:returns: the mode for os.open() — 0o666 when unset (let umask/ACLs decide), else the explicit mode""" return 0o666 if self._context.mode == _UNSET_FILE_MODE else self._context.mode
def _try_break_expired_lock(self) -> None: """Remove the lock file if its modification time exceeds the configured :attr:`lifetime`.""" if (lifetime := self._context.lifetime) is None: return with contextlib.suppress(OSError): if time.time() - pathlib.Path(self.lock_file).stat().st_mtime < lifetime: return break_path = f"{self.lock_file}.break.{os.getpid()}" pathlib.Path(self.lock_file).rename(break_path) pathlib.Path(break_path).unlink()
@abstractmethod def _acquire(self) -> None: """If the file lock could be acquired, self._context.lock_file_fd holds the file descriptor of the lock file.""" raise NotImplementedError
@abstractmethod def _release(self) -> None: """Releases the lock and sets self._context.lock_file_fd to None.""" raise NotImplementedError
@property def is_locked(self) -> bool: """ :returns: A boolean indicating if the lock file is holding the lock currently.
.. versionchanged:: 2.0.0
This was previously a method and is now a property.
""" return self._context.lock_file_fd is not None
@property def lock_counter(self) -> int: """:returns: The number of times this lock has been acquired (but not yet released).""" return self._context.lock_counter
@staticmethod def _check_give_up( # noqa: PLR0913 lock_id: int, lock_filename: str, *, blocking: bool, cancel_check: Callable[[], bool] | None, timeout: float, start_time: float, ) -> bool: if blocking is False: _LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename) return True if cancel_check is not None and cancel_check(): _LOGGER.debug("Cancellation requested for lock %s on %s", lock_id, lock_filename) return True if 0 <= timeout < time.perf_counter() - start_time: _LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename) return True return False
def acquire( # noqa: C901 self, timeout: float | None = None, poll_interval: float | None = None, *, poll_intervall: float | None = None, blocking: bool | None = None, cancel_check: Callable[[], bool] | None = None, ) -> AcquireReturnProxy: """ Try to acquire the file lock.
:param timeout: maximum wait time for acquiring the lock, ``None`` means use the default :attr:`~timeout` is and if ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired :param poll_interval: interval of trying to acquire the lock file, ``None`` means use the default :attr:`~poll_interval` :param poll_intervall: deprecated, kept for backwards compatibility, use ``poll_interval`` instead :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired. :param cancel_check: a callable returning ``True`` when the acquisition should be canceled. Checked on each poll iteration. When triggered, raises :class:`~Timeout` just like an expired timeout.
:returns: a context object that will unlock the file when the context is exited
:raises Timeout: if fails to acquire lock within the timeout period
.. code-block:: python
# You can use this method in the context manager (recommended) with lock.acquire(): pass
# Or use an equivalent try-finally construct: lock.acquire() try: pass finally: lock.release()
.. versionchanged:: 2.0.0
This method returns now a *proxy* object instead of *self*, so that it can be used in a with statement without side effects.
""" # Use the default timeout, if no timeout is provided. if timeout is None: timeout = self._context.timeout
if blocking is None: blocking = self._context.blocking
if poll_intervall is not None: msg = "use poll_interval instead of poll_intervall" warnings.warn(msg, DeprecationWarning, stacklevel=2) poll_interval = poll_intervall
poll_interval = poll_interval if poll_interval is not None else self._context.poll_interval
# Increment the number right at the beginning. We can still undo it, if something fails. self._context.lock_counter += 1
lock_id = id(self) lock_filename = self.lock_file canonical = _canonical(lock_filename)
would_block = self._context.lock_counter == 1 and not self.is_locked and timeout < 0 and blocking if would_block and (existing := _registry.held.get(canonical)) is not None and existing != lock_id: self._context.lock_counter -= 1 msg = ( f"Deadlock: lock '{lock_filename}' is already held by a different " f"FileLock instance in this thread. Use is_singleton=True to " f"enable reentrant locking across instances." ) raise RuntimeError(msg)
start_time = time.perf_counter() try: while True: if not self.is_locked: self._try_break_expired_lock() _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename) self._acquire() if self.is_locked: _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename) break if self._check_give_up( lock_id, lock_filename, blocking=blocking, cancel_check=cancel_check, timeout=timeout, start_time=start_time, ): raise Timeout(lock_filename) # noqa: TRY301 msg = "Lock %s not acquired on %s, waiting %s seconds ..." _LOGGER.debug(msg, lock_id, lock_filename, poll_interval) time.sleep(poll_interval) except BaseException: self._context.lock_counter = max(0, self._context.lock_counter - 1) if self._context.lock_counter == 0: _registry.held.pop(canonical, None) raise if self._context.lock_counter == 1: _registry.held[canonical] = lock_id return AcquireReturnProxy(lock=self)
def release(self, force: bool = False) -> None: # noqa: FBT001, FBT002 """ Release the file lock. The lock is only completely released when the lock counter reaches 0. The lock file itself is not automatically deleted.
:param force: If true, the lock counter is ignored and the lock is released in every case.
""" if self.is_locked: self._context.lock_counter -= 1
if self._context.lock_counter == 0 or force: lock_id, lock_filename = id(self), self.lock_file
_LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename) self._release() self._context.lock_counter = 0 _registry.held.pop(_canonical(lock_filename), None) _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename)
def __enter__(self) -> Self: """ Acquire the lock.
:returns: the lock object
""" self.acquire() return self
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: """ Release the lock.
:param exc_type: the exception type if raised :param exc_value: the exception value if raised :param traceback: the exception traceback if raised
""" self.release()
def __del__(self) -> None: """Called when the lock object is deleted.""" self.release(force=True)
__all__ = [ "_UNSET_FILE_MODE", "AcquireReturnProxy", "BaseFileLock",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207"""Async wrapper around :class:`ReadWriteLock` for use with ``asyncio``."""
from __future__ import annotations
import asyncioimport functoolsfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanagerfrom typing import TYPE_CHECKING
from ._read_write import ReadWriteLock
if TYPE_CHECKING: import os from collections.abc import AsyncGenerator, Callable from concurrent import futures from types import TracebackType
class AsyncAcquireReadWriteReturnProxy: """Context-aware object that releases the async read/write lock on exit."""
def __init__(self, lock: AsyncReadWriteLock) -> None: self.lock = lock
async def __aenter__(self) -> AsyncReadWriteLock: return self.lock
async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: await self.lock.release()
class AsyncReadWriteLock: """ Async wrapper around :class:`ReadWriteLock` for use in ``asyncio`` applications.
Because Python's :mod:`sqlite3` module has no async API, all blocking SQLite operations are dispatched to a thread pool via ``loop.run_in_executor()``. Reentrancy, upgrade/downgrade rules, and singleton behavior are delegated to the underlying :class:`ReadWriteLock`.
:param lock_file: path to the SQLite database file used as the lock :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable :param is_singleton: if ``True``, reuse existing :class:`ReadWriteLock` instances for the same resolved path :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop :param executor: executor for ``run_in_executor``; ``None`` uses the default executor
.. versionadded:: 3.21.0
"""
def __init__( # noqa: PLR0913 self, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True, is_singleton: bool = True, loop: asyncio.AbstractEventLoop | None = None, executor: futures.Executor | None = None, ) -> None: self._lock = ReadWriteLock(lock_file, timeout, blocking=blocking, is_singleton=is_singleton) self._loop = loop self._owns_executor = executor is None self._executor = executor or ThreadPoolExecutor(max_workers=1)
@property def lock_file(self) -> str: """:returns: the path to the lock file.""" return self._lock.lock_file
@property def timeout(self) -> float: """:returns: the default timeout.""" return self._lock.timeout
@property def blocking(self) -> bool: """:returns: whether blocking is enabled by default.""" return self._lock.blocking
@property def loop(self) -> asyncio.AbstractEventLoop | None: """:returns: the event loop (or ``None`` for the running loop).""" return self._loop
@property def executor(self) -> futures.Executor | None: """:returns: the executor (or ``None`` for the default).""" return self._executor
async def _run(self, func: Callable[..., object], *args: object, **kwargs: object) -> object: loop = self._loop or asyncio.get_running_loop() return await loop.run_in_executor(self._executor, functools.partial(func, *args, **kwargs))
async def acquire_read(self, timeout: float = -1, *, blocking: bool = True) -> AsyncAcquireReadWriteReturnProxy: """ Acquire a shared read lock.
See :meth:`ReadWriteLock.acquire_read` for full semantics.
:param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
:returns: a proxy that can be used as an async context manager to release the lock
:raises RuntimeError: if a write lock is already held on this instance :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" await self._run(self._lock.acquire_read, timeout, blocking=blocking) return AsyncAcquireReadWriteReturnProxy(lock=self)
async def acquire_write(self, timeout: float = -1, *, blocking: bool = True) -> AsyncAcquireReadWriteReturnProxy: """ Acquire an exclusive write lock.
See :meth:`ReadWriteLock.acquire_write` for full semantics.
:param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
:returns: a proxy that can be used as an async context manager to release the lock
:raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" await self._run(self._lock.acquire_write, timeout, blocking=blocking) return AsyncAcquireReadWriteReturnProxy(lock=self)
async def release(self, *, force: bool = False) -> None: """ Release one level of the current lock.
See :meth:`ReadWriteLock.release` for full semantics.
:param force: if ``True``, release the lock completely regardless of the current lock level
:raises RuntimeError: if no lock is currently held and *force* is ``False``
""" await self._run(self._lock.release, force=force)
@asynccontextmanager async def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: """ Async context manager that acquires and releases a shared read lock.
Falls back to instance defaults for *timeout* and *blocking* when ``None``.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
""" if timeout is None: timeout = self._lock.timeout if blocking is None: blocking = self._lock.blocking await self.acquire_read(timeout, blocking=blocking) try: yield finally: await self.release()
@asynccontextmanager async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: """ Async context manager that acquires and releases an exclusive write lock.
Falls back to instance defaults for *timeout* and *blocking* when ``None``.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
""" if timeout is None: timeout = self._lock.timeout if blocking is None: blocking = self._lock.blocking await self.acquire_write(timeout, blocking=blocking) try: yield finally: await self.release()
async def close(self) -> None: """ Release the lock (if held) and close the underlying SQLite connection.
After calling this method, the lock instance is no longer usable.
""" await self._run(self._lock.close) if self._owns_executor: self._executor.shutdown(wait=False)
__all__ = [ "AsyncAcquireReadWriteReturnProxy", "AsyncReadWriteLock",]123456789101112131415161718192021222324252627282930from __future__ import annotations
from typing import Any
class Timeout(TimeoutError): # noqa: N818 """Raised when the lock could not be acquired in *timeout* seconds."""
def __init__(self, lock_file: str) -> None: super().__init__() self._lock_file = lock_file
def __reduce__(self) -> str | tuple[Any, ...]: return self.__class__, (self._lock_file,) # Properly pickle the exception
def __str__(self) -> str: return f"The file lock '{self._lock_file}' could not be acquired."
def __repr__(self) -> str: return f"{self.__class__.__name__}({self.lock_file!r})"
@property def lock_file(self) -> str: """:returns: The path of the file lock.""" return self._lock_file
__all__ = [ "Timeout",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364from __future__ import annotations
import atexitimport loggingimport osimport pathlibimport sqlite3import threadingimport timefrom contextlib import contextmanager, suppressfrom typing import TYPE_CHECKING, Literalfrom weakref import WeakValueDictionary
from ._api import AcquireReturnProxyfrom ._error import Timeout
if TYPE_CHECKING: from collections.abc import Generator
_LOGGER = logging.getLogger("filelock")
_all_connections: set[sqlite3.Connection] = set()_all_connections_lock = threading.Lock()
def _cleanup_connections() -> None: with _all_connections_lock: for con in list(_all_connections): with suppress(Exception): con.close() _all_connections.clear()
atexit.register(_cleanup_connections)
# sqlite3_busy_timeout() accepts a C int, max 2_147_483_647 on 32-bit. Use a lower value to be safe (~23 days)._MAX_SQLITE_TIMEOUT_MS = 2_000_000_000 - 1
def timeout_for_sqlite(timeout: float, *, blocking: bool, already_waited: float) -> int: if blocking is False: return 0
if timeout == -1: return _MAX_SQLITE_TIMEOUT_MS
if timeout < 0: msg = "timeout must be a non-negative number or -1" raise ValueError(msg)
remaining = max(timeout - already_waited, 0) if timeout > 0 else timeout timeout_ms = int(remaining * 1000) if timeout_ms > _MAX_SQLITE_TIMEOUT_MS or timeout_ms < 0: _LOGGER.warning("timeout %s is too large for SQLite, using %s ms instead", timeout, _MAX_SQLITE_TIMEOUT_MS) return _MAX_SQLITE_TIMEOUT_MS return timeout_ms
class _ReadWriteLockMeta(type): """ Metaclass that handles singleton resolution when is_singleton=True.
Singleton logic lives here rather than in ReadWriteLock.get_lock so that ``ReadWriteLock(path)`` transparently returns cached instances without a 2-arg ``super()`` call that type checkers cannot verify.
"""
_instances: WeakValueDictionary[pathlib.Path, ReadWriteLock] _instances_lock: threading.Lock
def __call__( cls, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True, is_singleton: bool = True, ) -> ReadWriteLock: if not is_singleton: return super().__call__(lock_file, timeout, blocking=blocking, is_singleton=is_singleton)
normalized = pathlib.Path(lock_file).resolve() with cls._instances_lock: if normalized not in cls._instances: instance = super().__call__(lock_file, timeout, blocking=blocking, is_singleton=is_singleton) cls._instances[normalized] = instance else: instance = cls._instances[normalized]
if instance.timeout != timeout or instance.blocking != blocking: msg = ( f"Singleton lock created with timeout={instance.timeout}, blocking={instance.blocking}," f" cannot be changed to timeout={timeout}, blocking={blocking}" ) raise ValueError(msg) return instance
class ReadWriteLock(metaclass=_ReadWriteLockMeta): """ Cross-process read-write lock backed by SQLite.
Allows concurrent shared readers or a single exclusive writer. The lock is reentrant within the same mode (multiple ``acquire_read`` calls nest, as do multiple ``acquire_write`` calls from the same thread), but upgrading from read to write or downgrading from write to read raises :class:`RuntimeError`. Write locks are pinned to the thread that acquired them.
By default, ``is_singleton=True``: calling ``ReadWriteLock(path)`` with the same resolved path returns the same instance. The lock file must use a ``.db`` extension (SQLite database).
:param lock_file: path to the SQLite database file used as the lock :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable :param is_singleton: if ``True``, reuse existing instances for the same resolved path
.. versionadded:: 3.21.0
"""
_instances: WeakValueDictionary[pathlib.Path, ReadWriteLock] = WeakValueDictionary() _instances_lock = threading.Lock()
@classmethod def get_lock( cls, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True ) -> ReadWriteLock: """ Return the singleton :class:`ReadWriteLock` for *lock_file*.
:param lock_file: path to the SQLite database file used as the lock :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
:returns: the singleton lock instance
:raises ValueError: if an instance already exists for this path with different *timeout* or *blocking* values
""" return cls(lock_file, timeout, blocking=blocking)
def __init__( self, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True, is_singleton: bool = True, # noqa: ARG002 # consumed by _ReadWriteLockMeta.__call__ ) -> None: self.lock_file = os.fspath(lock_file) self.timeout = timeout self.blocking = blocking self._transaction_lock = threading.Lock() # serializes the (possibly blocking) SQLite transaction work self._internal_lock = threading.Lock() # protects _lock_level / _current_mode updates and rollback self._lock_level = 0 self._current_mode: Literal["read", "write"] | None = None self._write_thread_id: int | None = None self._con = sqlite3.connect(self.lock_file, check_same_thread=False) with _all_connections_lock: _all_connections.add(self._con)
def _acquire_transaction_lock(self, *, blocking: bool, timeout: float) -> None: if not blocking: acquired = self._transaction_lock.acquire(blocking=False) elif timeout == -1: acquired = self._transaction_lock.acquire(blocking=True) else: acquired = self._transaction_lock.acquire(blocking=True, timeout=timeout) if not acquired: raise Timeout(self.lock_file) from None
def _validate_reentrant(self, mode: Literal["read", "write"], opposite: str, direction: str) -> AcquireReturnProxy: if self._current_mode != mode: msg = ( f"Cannot acquire {mode} lock on {self.lock_file} (lock id: {id(self)}): " f"already holding a {opposite} lock ({direction} not allowed)" ) raise RuntimeError(msg) if mode == "write" and (cur := threading.get_ident()) != self._write_thread_id: msg = ( f"Cannot acquire write lock on {self.lock_file} (lock id: {id(self)}) " f"from thread {cur} while it is held by thread {self._write_thread_id}" ) raise RuntimeError(msg) self._lock_level += 1 return AcquireReturnProxy(lock=self)
def _configure_and_begin( self, mode: Literal["read", "write"], timeout: float, *, blocking: bool, start_time: float ) -> None: waited = time.perf_counter() - start_time timeout_ms = timeout_for_sqlite(timeout, blocking=blocking, already_waited=waited) self._con.execute(f"PRAGMA busy_timeout={timeout_ms};").close() # Use legacy journal mode (not WAL) because WAL does not block readers when a concurrent EXCLUSIVE # write transaction is active, making read-write locking impossible without modifying table data. # MEMORY is safe here since no actual writes happen — crashes cannot corrupt the DB. # See https://sqlite.org/lang_transaction.html#deferred_immediate_and_exclusive_transactions # # Set here (not in __init__) because this pragma itself may block on a locked database, # so it must run after busy_timeout is configured above. self._con.execute("PRAGMA journal_mode=MEMORY;").close() # Recompute remaining timeout after the potentially blocking journal_mode pragma. waited = time.perf_counter() - start_time if (recomputed := timeout_for_sqlite(timeout, blocking=blocking, already_waited=waited)) != timeout_ms: self._con.execute(f"PRAGMA busy_timeout={recomputed};").close() stmt = "BEGIN EXCLUSIVE TRANSACTION;" if mode == "write" else "BEGIN TRANSACTION;" self._con.execute(stmt).close() if mode == "read": # A SELECT is needed to force SQLite to actually acquire the SHARED lock on the database. # https://www.sqlite.org/lockingv3.html#transaction_control self._con.execute("SELECT name FROM sqlite_schema LIMIT 1;").close()
def _acquire(self, mode: Literal["read", "write"], timeout: float, *, blocking: bool) -> AcquireReturnProxy: opposite = "write" if mode == "read" else "read" direction = "downgrade" if mode == "read" else "upgrade"
with self._internal_lock: if self._lock_level > 0: return self._validate_reentrant(mode, opposite, direction)
start_time = time.perf_counter() self._acquire_transaction_lock(blocking=blocking, timeout=timeout) try: # Double-check: another thread may have acquired the lock while we waited on _transaction_lock. with self._internal_lock: if self._lock_level > 0: return self._validate_reentrant(mode, opposite, direction)
self._configure_and_begin(mode, timeout, blocking=blocking, start_time=start_time)
with self._internal_lock: self._current_mode = mode self._lock_level = 1 if mode == "write": self._write_thread_id = threading.get_ident()
return AcquireReturnProxy(lock=self)
except sqlite3.OperationalError as exc: if "database is locked" not in str(exc): raise raise Timeout(self.lock_file) from None finally: self._transaction_lock.release()
def acquire_read(self, timeout: float = -1, *, blocking: bool = True) -> AcquireReturnProxy: """ Acquire a shared read lock.
If this instance already holds a read lock, the lock level is incremented (reentrant). Attempting to acquire a read lock while holding a write lock raises :class:`RuntimeError` (downgrade not allowed).
:param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
:returns: a proxy that can be used as a context manager to release the lock
:raises RuntimeError: if a write lock is already held on this instance :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" return self._acquire("read", timeout, blocking=blocking)
def acquire_write(self, timeout: float = -1, *, blocking: bool = True) -> AcquireReturnProxy: """ Acquire an exclusive write lock.
If this instance already holds a write lock from the same thread, the lock level is incremented (reentrant). Attempting to acquire a write lock while holding a read lock raises :class:`RuntimeError` (upgrade not allowed). Write locks are pinned to the acquiring thread: a different thread trying to re-enter also raises :class:`RuntimeError`.
:param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
:returns: a proxy that can be used as a context manager to release the lock
:raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" return self._acquire("write", timeout, blocking=blocking)
def release(self, *, force: bool = False) -> None: """ Release one level of the current lock.
When the lock level reaches zero the underlying SQLite transaction is rolled back, releasing the database lock.
:param force: if ``True``, release the lock completely regardless of the current lock level
:raises RuntimeError: if no lock is currently held and *force* is ``False``
""" should_rollback = False with self._internal_lock: if self._lock_level == 0: if force: return msg = f"Cannot release a lock on {self.lock_file} (lock id: {id(self)}) that is not held" raise RuntimeError(msg) if force: self._lock_level = 0 else: self._lock_level -= 1 if self._lock_level == 0: self._current_mode = None self._write_thread_id = None should_rollback = True if should_rollback: self._con.rollback()
@contextmanager def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: """ Context manager that acquires and releases a shared read lock.
Falls back to instance defaults for *timeout* and *blocking* when ``None``.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
""" if timeout is None: timeout = self.timeout if blocking is None: blocking = self.blocking self.acquire_read(timeout, blocking=blocking) try: yield finally: self.release()
@contextmanager def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: """ Context manager that acquires and releases an exclusive write lock.
Falls back to instance defaults for *timeout* and *blocking* when ``None``.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
""" if timeout is None: timeout = self.timeout if blocking is None: blocking = self.blocking self.acquire_write(timeout, blocking=blocking) try: yield finally: self.release()
def close(self) -> None: """ Release the lock (if held) and close the underlying SQLite connection.
After calling this method, the lock instance is no longer usable.
""" self.release(force=True) self._con.close() with _all_connections_lock: _all_connections.discard(self._con)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214from __future__ import annotations
import osimport socketimport sysimport timefrom contextlib import suppressfrom errno import EACCES, EEXIST, EPERM, ESRCHfrom pathlib import Path
from ._api import BaseFileLockfrom ._util import ensure_directory_exists, raise_on_not_writable_file
_WIN_SYNCHRONIZE = 0x100000_WIN_ERROR_INVALID_PARAMETER = 87_WIN_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000_MALFORMED_LOCK_AGE_THRESHOLD = 2.0
class SoftFileLock(BaseFileLock): """ Portable file lock based on file existence.
Unlike :class:`UnixFileLock <filelock.UnixFileLock>` and :class:`WindowsFileLock <filelock.WindowsFileLock>`, this lock does not use OS-level locking primitives. Instead, it creates the lock file with ``O_CREAT | O_EXCL`` and treats its existence as the lock indicator. This makes it work on any filesystem but leaves stale lock files behind if the process crashes without releasing the lock.
To mitigate stale locks, the lock file contains the PID and hostname of the holding process. On contention, if the holder is on the same host and its PID no longer exists, the stale lock is broken automatically.
"""
def _acquire(self) -> None: raise_on_not_writable_file(self.lock_file) ensure_directory_exists(self.lock_file) flags = ( os.O_WRONLY # open for writing only | os.O_CREAT | os.O_EXCL # together with above raise EEXIST if the file specified by filename exists | os.O_TRUNC # truncate the file to zero byte ) if (o_nofollow := getattr(os, "O_NOFOLLOW", None)) is not None: flags |= o_nofollow try: file_handler = os.open(self.lock_file, flags, self._open_mode()) except OSError as exception: if not ( exception.errno == EEXIST or (exception.errno == EACCES and sys.platform == "win32") ): # pragma: win32 no cover raise self._try_break_stale_lock() else: self._write_lock_info(file_handler) self._context.lock_file_fd = file_handler
def _try_break_stale_lock(self) -> None: with suppress(OSError, ValueError): lock_path = Path(self.lock_file) stat_result = lock_path.stat() content = lock_path.read_text(encoding="utf-8") lines = content.strip().splitlines()
if len(lines) not in {2, 3}: if time.time() - stat_result.st_mtime >= _MALFORMED_LOCK_AGE_THRESHOLD: self._evict_lock_file() return
pid_str, hostname = lines[0], lines[1] creation_time_str = lines[2] if len(lines) == 3 else None # noqa: PLR2004
if hostname != socket.gethostname(): return
pid = int(pid_str)
if self._is_process_alive(pid): if sys.platform == "win32" and creation_time_str is not None: # pragma: win32 cover stored = int(creation_time_str) actual = self._get_process_creation_time(pid) if actual is not None and actual != stored: pass # PID recycled, fall through to evict else: return # same process or can't verify — don't evict else: return
self._evict_lock_file()
def _evict_lock_file(self) -> None: break_path = f"{self.lock_file}.break.{os.getpid()}" Path(self.lock_file).rename(break_path) Path(break_path).unlink()
@staticmethod def _is_process_alive(pid: int) -> bool: if sys.platform == "win32": # pragma: win32 cover import ctypes # noqa: PLC0415
kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(_WIN_SYNCHRONIZE, 0, pid) if handle: kernel32.CloseHandle(handle) return True return kernel32.GetLastError() != _WIN_ERROR_INVALID_PARAMETER try: os.kill(pid, 0) except OSError as exc: if exc.errno == ESRCH: return False if exc.errno == EPERM: return True raise return True
@staticmethod def _get_process_creation_time(pid: int) -> int | None: """Return the process creation FILETIME as an integer on Windows, ``None`` otherwise.""" if sys.platform != "win32": # pragma: win32 no cover return None import ctypes # pragma: win32 cover # noqa: PLC0415 from ctypes import wintypes # noqa: PLC0415
kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(_WIN_PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) if not handle: return None try: creation = wintypes.FILETIME() exit_time = wintypes.FILETIME() kernel_time = wintypes.FILETIME() user_time = wintypes.FILETIME() if not kernel32.GetProcessTimes( handle, ctypes.byref(creation), ctypes.byref(exit_time), ctypes.byref(kernel_time), ctypes.byref(user_time), ): return None finally: kernel32.CloseHandle(handle) return (creation.dwHighDateTime << 32) | creation.dwLowDateTime
@staticmethod def _write_lock_info(fd: int) -> None: with suppress(OSError): info = f"{os.getpid()}\n{socket.gethostname()}\n" if sys.platform == "win32" and (ct := SoftFileLock._get_process_creation_time(os.getpid())) is not None: info += f"{ct}\n" os.write(fd, info.encode())
@property def pid(self) -> int | None: """ The PID of the process holding this lock, read from the lock file.
:returns: the PID as an integer, or ``None`` if the lock file does not exist or cannot be parsed
""" try: content = Path(self.lock_file).read_text(encoding="utf-8") lines = content.strip().splitlines() if lines: return int(lines[0]) except (OSError, ValueError): pass return None
@property def is_lock_held_by_us(self) -> bool: """ Whether this lock is held by the current process.
:returns: ``True`` if the lock file exists and contains the current process's PID
""" return self.pid == os.getpid()
def break_lock(self) -> None: """Forcibly break the lock by removing the lock file, regardless of who holds it.""" with suppress(OSError): Path(self.lock_file).unlink()
def _release(self) -> None: assert self._context.lock_file_fd is not None # noqa: S101 os.close(self._context.lock_file_fd) self._context.lock_file_fd = None if sys.platform == "win32": self._windows_unlink_with_retry() else: with suppress(OSError): Path(self.lock_file).unlink()
def _windows_unlink_with_retry(self) -> None: max_retries = 10 retry_delay = 0.001 for attempt in range(max_retries): # Windows doesn't immediately release file handles after close, causing EACCES/EPERM on unlink try: Path(self.lock_file).unlink() except OSError as exc: # noqa: PERF203 if exc.errno not in {EACCES, EPERM}: return if attempt < max_retries - 1: time.sleep(retry_delay) retry_delay *= 2 else: return
__all__ = [ "SoftFileLock",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213"""Async wrapper around :class:`SoftReadWriteLock` for use with ``asyncio``."""
from __future__ import annotations
import asyncioimport functoolsfrom contextlib import asynccontextmanagerfrom typing import TYPE_CHECKING
from ._sync import SoftReadWriteLock
if TYPE_CHECKING: import os from collections.abc import AsyncGenerator, Callable from concurrent import futures from types import TracebackType
class AsyncAcquireSoftReadWriteReturnProxy: """Async context-aware object that releases an :class:`AsyncSoftReadWriteLock` on exit."""
def __init__(self, lock: AsyncSoftReadWriteLock) -> None: self.lock = lock
async def __aenter__(self) -> AsyncSoftReadWriteLock: return self.lock
async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: await self.lock.release()
class AsyncSoftReadWriteLock: """ Async wrapper around :class:`SoftReadWriteLock` for ``asyncio`` applications.
The sync class's blocking filesystem operations run on a thread pool via ``loop.run_in_executor()``. Reentrancy, upgrade/downgrade rules, fork handling, heartbeat and TTL stale detection, and singleton behavior are delegated to the underlying :class:`SoftReadWriteLock`.
:param lock_file: path to the lock file; sidecar state/write/readers live next to it :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately on contention :param is_singleton: if ``True``, reuse existing :class:`SoftReadWriteLock` instances per resolved path :param heartbeat_interval: seconds between heartbeat refreshes; default 30 s :param stale_threshold: seconds of mtime inactivity before a marker is stale; defaults to ``3 * heartbeat_interval`` :param poll_interval: seconds between acquire retries under contention; default 0.25 s :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop :param executor: executor for ``run_in_executor``; ``None`` uses the default executor
.. versionadded:: 3.27.0
"""
def __init__( # noqa: PLR0913 self, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True, is_singleton: bool = True, heartbeat_interval: float = 30.0, stale_threshold: float | None = None, poll_interval: float = 0.25, loop: asyncio.AbstractEventLoop | None = None, executor: futures.Executor | None = None, ) -> None: self._lock = SoftReadWriteLock( lock_file, timeout, blocking=blocking, is_singleton=is_singleton, heartbeat_interval=heartbeat_interval, stale_threshold=stale_threshold, poll_interval=poll_interval, ) self._loop = loop self._executor = executor
@property def lock_file(self) -> str: """:returns: the path to the lock file passed to the constructor.""" return self._lock.lock_file
@property def timeout(self) -> float: """:returns: the default timeout applied when ``acquire_read`` / ``acquire_write`` is called without one.""" return self._lock.timeout
@property def blocking(self) -> bool: """:returns: whether ``acquire_*`` defaults to blocking; ``False`` makes contention raise immediately.""" return self._lock.blocking
@property def loop(self) -> asyncio.AbstractEventLoop | None: """:returns: the event loop used for ``run_in_executor``, or ``None`` for the running loop.""" return self._loop
@property def executor(self) -> futures.Executor | None: """:returns: the executor used for ``run_in_executor``, or ``None`` for the default executor.""" return self._executor
async def acquire_read( self, timeout: float | None = None, *, blocking: bool | None = None ) -> AsyncAcquireSoftReadWriteReturnProxy: """ Acquire a shared read lock.
See :meth:`SoftReadWriteLock.acquire_read` for the full reentrancy / upgrade / fork semantics. The blocking work runs inside ``run_in_executor`` so other coroutines on the same loop continue to progress while this call waits.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
:returns: a proxy usable as an async context manager to release the lock
:raises RuntimeError: if a write lock is already held, if this instance was invalidated by :func:`os.fork`, or if :meth:`close` was called :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" await self._run(self._lock.acquire_read, timeout, blocking=blocking) return AsyncAcquireSoftReadWriteReturnProxy(lock=self)
async def acquire_write( self, timeout: float | None = None, *, blocking: bool | None = None ) -> AsyncAcquireSoftReadWriteReturnProxy: """ Acquire an exclusive write lock.
See :meth:`SoftReadWriteLock.acquire_write` for the two-phase writer-preferring semantics. The blocking work runs inside ``run_in_executor``.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
:returns: a proxy usable as an async context manager to release the lock
:raises RuntimeError: if a read lock is already held, if a write lock is held by a different thread, if this instance was invalidated by :func:`os.fork`, or if :meth:`close` was called :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" await self._run(self._lock.acquire_write, timeout, blocking=blocking) return AsyncAcquireSoftReadWriteReturnProxy(lock=self)
async def release(self, *, force: bool = False) -> None: """ Release one level of the current lock.
:param force: if ``True``, release the lock completely regardless of the current lock level
:raises RuntimeError: if no lock is currently held and *force* is ``False``
""" await self._run(self._lock.release, force=force)
@asynccontextmanager async def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: """ Async context manager that acquires and releases a shared read lock.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
:raises RuntimeError: if a write lock is already held on this instance :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" await self.acquire_read(timeout, blocking=blocking) try: yield finally: await self.release()
@asynccontextmanager async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: """ Async context manager that acquires and releases an exclusive write lock.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
:raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" await self.acquire_write(timeout, blocking=blocking) try: yield finally: await self.release()
async def close(self) -> None: """Release any held lock and release the underlying filesystem resources. Idempotent.""" await self._run(self._lock.close)
async def _run(self, func: Callable[..., object], *args: object, **kwargs: object) -> object: loop = self._loop or asyncio.get_running_loop() return await loop.run_in_executor(self._executor, functools.partial(func, *args, **kwargs))
__all__ = [ "AsyncAcquireSoftReadWriteReturnProxy", "AsyncSoftReadWriteLock",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847"""Cross-process and cross-host reader/writer lock built on :class:`SoftFileLock` primitives."""
from __future__ import annotations
import atexitimport hmacimport osimport reimport secretsimport socketimport statimport sysimport threadingimport timeimport uuidfrom contextlib import contextmanager, suppressfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import TYPE_CHECKING, Literalfrom weakref import WeakValueDictionary
from filelock._api import AcquireReturnProxyfrom filelock._error import Timeoutfrom filelock._soft import SoftFileLockfrom filelock._util import ensure_directory_exists
if TYPE_CHECKING: from collections.abc import Callable, Generator
_Mode = Literal["read", "write"]_BREAK_SUFFIX = ".break"_MAX_MARKER_SIZE = 1024_O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)# dirfd-relative I/O is a Unix-only optimization; Windows cannot ``os.open()`` a directory at all, and# its ``os`` module skips dir_fd support entirely. When disabled, callers fall back to full-path ops._SUPPORTS_DIR_FD = sys.platform != "win32" and os.open in os.supports_dir_fd
_all_instances: WeakValueDictionary[Path, SoftReadWriteLock] = WeakValueDictionary()_all_instances_lock = threading.Lock()_atexit_registered = False_fork_registered = False
@dataclass(frozen=True)class _Paths: state: str write: str readers: str
@dataclassclass _Locks: internal: threading.Lock transaction: threading.Lock state: SoftFileLock
@dataclass(frozen=True)class _MarkerInfo: token: str pid: int hostname: str
@dataclassclass _Hold: """Everything that exists only while a lock is held; ``None`` when the instance has no lock."""
level: int mode: _Mode write_thread_id: int | None marker_name: str is_reader: bool token: str heartbeat_thread: _HeartbeatThread heartbeat_stop: threading.Event
class _SoftRWMeta(type): _instances: WeakValueDictionary[Path, SoftReadWriteLock] _instances_lock: threading.Lock
def __call__( # noqa: PLR0913 cls, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True, is_singleton: bool = True, heartbeat_interval: float = 30.0, stale_threshold: float | None = None, poll_interval: float = 0.25, ) -> SoftReadWriteLock: if not is_singleton: return super().__call__( lock_file, timeout, blocking=blocking, is_singleton=is_singleton, heartbeat_interval=heartbeat_interval, stale_threshold=stale_threshold, poll_interval=poll_interval, )
normalized = Path(lock_file).resolve() with cls._instances_lock: instance = cls._instances.get(normalized) if instance is None: instance = super().__call__( lock_file, timeout, blocking=blocking, is_singleton=is_singleton, heartbeat_interval=heartbeat_interval, stale_threshold=stale_threshold, poll_interval=poll_interval, ) cls._instances[normalized] = instance elif instance.timeout != timeout or instance.blocking != blocking: msg = ( f"Singleton lock created with timeout={instance.timeout}, blocking={instance.blocking}," f" cannot be changed to timeout={timeout}, blocking={blocking}" ) raise ValueError(msg) return instance
class SoftReadWriteLock(metaclass=_SoftRWMeta): """ Cross-process and cross-host reader/writer lock built on :class:`SoftFileLock` primitives.
Use this class instead of :class:`~filelock.ReadWriteLock` when the lock file lives on a network filesystem (NFS, Lustre with ``-o flock``, HPC cluster shared storage). ``ReadWriteLock`` is backed by SQLite and cannot run on NFS because SQLite's ``fcntl`` locking is unreliable there.
Layout on disk for a lock at ``foo.lock``:
- ``foo.lock.state`` — a :class:`SoftFileLock` taken only during state transitions (microseconds). - ``foo.lock.write`` — writer marker; its presence means a writer is claiming or holding the lock. - ``foo.lock.readers/<host>.<pid>.<uuid>`` — one file per reader.
Each marker stores a random token (``secrets.token_hex(16)``), the holder's pid, and the holder's hostname. A daemon heartbeat thread refreshes ``mtime`` on every held marker. A marker whose mtime has not advanced in ``stale_threshold`` seconds may be evicted by any process on any host, giving correct behavior when a compute node crashes with a lock held.
Writer acquire is two-phase and writer-preferring: phase 1 claims ``.write`` (blocking any new reader), phase 2 waits for existing readers to drain. Writer starvation is impossible.
Reentrancy, upgrade/downgrade rules, thread pinning, and singleton caching by resolved path match :class:`~filelock.ReadWriteLock`.
Forking while holding a lock invalidates the inherited instance in the child so the child cannot double-own the lock with its parent; ``release()`` on a fork-invalidated instance is a no-op, and the child must re-acquire if it needs a lock.
Trust boundary: protects against same-UID non-cooperating processes (one host or cross-host) and same-host different-UID users via ``0o600`` / ``0o700`` permissions. Does not protect against root compromise, NTP tampering on same-UID cross-host nodes, or multi-tenant mounts where hostile co-tenants share the UID.
:param lock_file: path to the lock file; sidecar state/write/readers live next to it :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately on contention :param is_singleton: if ``True``, reuse existing instances for the same resolved path :param heartbeat_interval: seconds between heartbeat refreshes; default 30 s :param stale_threshold: seconds of ``mtime`` inactivity before a marker is stale; defaults to ``3 * heartbeat_interval``, matching etcd's ``LeaseKeepAlive`` convention :param poll_interval: seconds between acquire retries under contention; default 0.25 s
.. versionadded:: 3.27.0
"""
_instances: WeakValueDictionary[Path, SoftReadWriteLock] = WeakValueDictionary() _instances_lock = threading.Lock()
def __init__( # noqa: PLR0913 self, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True, is_singleton: bool = True, # noqa: ARG002 heartbeat_interval: float = 30.0, stale_threshold: float | None = None, poll_interval: float = 0.25, ) -> None: if heartbeat_interval <= 0: msg = f"heartbeat_interval must be positive, got {heartbeat_interval}" raise ValueError(msg) if stale_threshold is None: stale_threshold = heartbeat_interval * 3 if stale_threshold <= heartbeat_interval: msg = f"stale_threshold must exceed heartbeat_interval ({stale_threshold} <= {heartbeat_interval})" raise ValueError(msg) if poll_interval <= 0: msg = f"poll_interval must be positive, got {poll_interval}" raise ValueError(msg)
self.lock_file: str = os.fspath(lock_file) self.timeout: float = timeout self.blocking: bool = blocking self.heartbeat_interval: float = heartbeat_interval self.stale_threshold: float = stale_threshold self.poll_interval: float = poll_interval
self._paths = _Paths( state=f"{self.lock_file}.state", write=f"{self.lock_file}.write", readers=f"{self.lock_file}.readers", ) ensure_directory_exists(self.lock_file) self._locks = _Locks( internal=threading.Lock(), transaction=threading.Lock(), state=SoftFileLock(self._paths.state, timeout=-1), ) self._readers_dir_fd: int | None = None self._hold: _Hold | None = None self._fork_invalidated: bool = False self._closed: bool = False
with _all_instances_lock: _all_instances[Path(self.lock_file).resolve()] = self _register_hooks()
@contextmanager def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: """ Context manager that acquires and releases a shared read lock.
Falls back to instance defaults for *timeout* and *blocking* when ``None``.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
:raises RuntimeError: if a write lock is already held on this instance :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" self.acquire_read(timeout, blocking=blocking) try: yield finally: self.release()
@contextmanager def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: """ Context manager that acquires and releases an exclusive write lock.
Falls back to instance defaults for *timeout* and *blocking* when ``None``.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
:raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" self.acquire_write(timeout, blocking=blocking) try: yield finally: self.release()
def acquire_read(self, timeout: float | None = None, *, blocking: bool | None = None) -> AcquireReturnProxy: """ Acquire a shared read lock.
If this instance already holds a read lock, the lock level is incremented (reentrant). Attempting to acquire a read lock while holding a write lock raises :class:`RuntimeError` (downgrade not allowed). On the 0→1 transition a daemon heartbeat thread is started that refreshes the reader marker's ``mtime`` every ``heartbeat_interval`` seconds so peers on other hosts do not evict the marker as stale.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable; ``None`` uses the instance default
:returns: a proxy that can be used as a context manager to release the lock
:raises RuntimeError: if a write lock is already held on this instance, if this instance was invalidated by :func:`os.fork`, or if :meth:`close` was called :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" return self._acquire("read", timeout, blocking=blocking)
def acquire_write(self, timeout: float | None = None, *, blocking: bool | None = None) -> AcquireReturnProxy: """ Acquire an exclusive write lock.
If this instance already holds a write lock from the same thread, the lock level is incremented (reentrant). Attempting to acquire a write lock while holding a read lock raises :class:`RuntimeError` (upgrade not allowed). Write locks are pinned to the acquiring thread: a different thread trying to re-enter also raises :class:`RuntimeError`.
Writer acquisition runs in two phases. Phase 1 atomically claims ``<path>.write`` via ``O_CREAT | O_EXCL``, which immediately blocks any new reader on any host. Phase 2 waits for existing readers to drain. Writer starvation is impossible: new readers see ``<path>.write`` during phase 2 and wait behind the pending writer.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable; ``None`` uses the instance default
:returns: a proxy that can be used as a context manager to release the lock
:raises RuntimeError: if a read lock is already held, if a write lock is held by a different thread, if this instance was invalidated by :func:`os.fork`, or if :meth:`close` was called :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" return self._acquire("write", timeout, blocking=blocking)
def close(self) -> None: """ Release any held lock and release internal filesystem resources.
Idempotent. After calling this method the instance can no longer acquire locks — subsequent acquires raise :class:`RuntimeError`. A fork-invalidated instance is closed without raising. """ self.release(force=True) with self._locks.internal: if self._closed: return self._closed = True if self._readers_dir_fd is not None: with suppress(OSError): os.close(self._readers_dir_fd) self._readers_dir_fd = None
def release(self, *, force: bool = False) -> None: """ Release one level of the current lock.
When the lock level reaches zero the heartbeat thread is stopped and the held marker file is unlinked. On a fork-invalidated instance (that is, the child of a :func:`os.fork` call made while the parent held a lock) this method is a no-op so inherited ``with`` blocks can unwind cleanly in the child.
:param force: if ``True``, release the lock completely regardless of the current lock level
:raises RuntimeError: if no lock is currently held and *force* is ``False``
""" with self._locks.internal: if self._fork_invalidated: # Inherited state from the parent is meaningless in the child; clear any counters and return. self._hold = None return hold = self._hold if hold is None: if force: return msg = f"Cannot release a lock on {self.lock_file} (lock id: {id(self)}) that is not held" raise RuntimeError(msg) if force: hold.level = 0 else: hold.level -= 1 if hold.level > 0: return self._hold = None
# Order matters: signal → join → unlink. A late tick on a deleted marker is harmless, and the # token check in the heartbeat callback would catch any re-acquisition race, but joining first # removes even that theoretical race. hold.heartbeat_stop.set() hold.heartbeat_thread.join(timeout=self.heartbeat_interval + 1.0) if hold.is_reader: _unlink(hold.marker_name, dir_fd=self._readers_dir_fd) else: _unlink(hold.marker_name)
@classmethod def get_lock( cls, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True, ) -> SoftReadWriteLock: """ Return the singleton :class:`SoftReadWriteLock` for *lock_file*.
:param lock_file: path to the lock file; sidecar state/write/readers live next to it :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
:returns: the singleton lock instance
:raises ValueError: if an instance already exists for this path with different *timeout* or *blocking* values
""" return cls(lock_file, timeout, blocking=blocking)
def _acquire( self, mode: _Mode, timeout: float | None, *, blocking: bool | None, ) -> AcquireReturnProxy: effective_timeout = self.timeout if timeout is None else timeout effective_blocking = self.blocking if blocking is None else blocking
with self._locks.internal: if self._fork_invalidated: msg = f"SoftReadWriteLock on {self.lock_file} was invalidated by fork(); construct a new instance" raise RuntimeError(msg) if self._closed: msg = f"SoftReadWriteLock on {self.lock_file} has been closed" raise RuntimeError(msg) if self._hold is not None: return self._validate_reentrant(mode)
start = time.perf_counter() if not effective_blocking: acquired = self._locks.transaction.acquire(blocking=False) elif effective_timeout == -1: acquired = self._locks.transaction.acquire(blocking=True) else: acquired = self._locks.transaction.acquire(blocking=True, timeout=effective_timeout) if not acquired: raise Timeout(self.lock_file) from None try: with self._locks.internal: if self._hold is not None: return self._validate_reentrant(mode)
deadline = None if effective_timeout == -1 else start + effective_timeout token = secrets.token_hex(16) if mode == "write": marker_name, is_reader = self._acquire_writer_slot( token, deadline=deadline, blocking=effective_blocking ) else: marker_name, is_reader = self._acquire_reader_slot( token, deadline=deadline, blocking=effective_blocking )
stop_event = threading.Event() heartbeat = _HeartbeatThread( refresh=self._refresh_marker, interval=self.heartbeat_interval, stop_event=stop_event, name=f"filelock-heartbeat-{id(self):x}", )
with self._locks.internal: self._hold = _Hold( level=1, mode=mode, write_thread_id=threading.get_ident() if mode == "write" else None, marker_name=marker_name, is_reader=is_reader, token=token, heartbeat_thread=heartbeat, heartbeat_stop=stop_event, )
heartbeat.start() return AcquireReturnProxy(lock=self) finally: self._locks.transaction.release()
def _validate_reentrant(self, mode: _Mode) -> AcquireReturnProxy: hold = self._hold assert hold is not None # noqa: S101 if hold.mode != mode: opposite = "write" if mode == "read" else "read" direction = "downgrade" if mode == "read" else "upgrade" msg = ( f"Cannot acquire {mode} lock on {self.lock_file} (lock id: {id(self)}): " f"already holding a {opposite} lock ({direction} not allowed)" ) raise RuntimeError(msg) if mode == "write" and (cur := threading.get_ident()) != hold.write_thread_id: msg = ( f"Cannot acquire write lock on {self.lock_file} (lock id: {id(self)}) " f"from thread {cur} while it is held by thread {hold.write_thread_id}" ) raise RuntimeError(msg) hold.level += 1 return AcquireReturnProxy(lock=self)
def _acquire_writer_slot( self, token: str, *, deadline: float | None, blocking: bool, ) -> tuple[str, bool]: # Phase 2 scans readers/ via dirfd (where supported), so we need it open even though writers never # create files inside. self._open_readers_dir()
def try_claim_writer() -> bool: with self._locks.state: _break_stale_marker(self._paths.write, stale_threshold=self.stale_threshold, now=time.time()) if _file_exists(self._paths.write): return False try: _atomic_create_marker(self._paths.write, token) except FileExistsError: return False return True
def readers_drained_touching() -> bool: with self._locks.state: # Refresh our writer marker on every scan iteration. Otherwise phase 2 can exceed # ``stale_threshold`` under contention and a peer would treat us as stale and evict us. with suppress(OSError): _touch(self._paths.write) self._break_stale_readers(time.time()) return not self._any_readers()
self._wait_for(try_claim_writer, deadline=deadline, blocking=blocking) try: self._wait_for(readers_drained_touching, deadline=deadline, blocking=blocking) except Timeout: # Give up our writer claim so readers can make progress again. _unlink(self._paths.write) raise return self._paths.write, False
def _acquire_reader_slot( self, token: str, *, deadline: float | None, blocking: bool, ) -> tuple[str, bool]: self._open_readers_dir() reader_name = f"{uuid.uuid4().hex}.{os.getpid()}" dir_fd = self._readers_dir_fd full_reader_path = str(Path(self._paths.readers) / reader_name)
def try_claim_reader() -> bool: with self._locks.state: _break_stale_marker(self._paths.write, stale_threshold=self.stale_threshold, now=time.time()) if _file_exists(self._paths.write): return False if dir_fd is not None: _atomic_create_marker(reader_name, token, dir_fd=dir_fd) else: # pragma: win32 cover _atomic_create_marker(full_reader_path, token) return True
self._wait_for(try_claim_reader, deadline=deadline, blocking=blocking) return (reader_name if dir_fd is not None else full_reader_path), True
def _wait_for( self, predicate: Callable[[], bool], *, deadline: float | None, blocking: bool, ) -> None: while True: if predicate(): return now = time.perf_counter() if not blocking: raise Timeout(self.lock_file) if deadline is not None and now >= deadline: raise Timeout(self.lock_file) sleep_for = self.poll_interval if deadline is not None: sleep_for = min(sleep_for, max(deadline - now, 0.0)) time.sleep(sleep_for)
def _open_readers_dir(self) -> None: readers_path = Path(self._paths.readers) with suppress(FileExistsError): readers_path.mkdir(mode=0o700) # mkdir has no O_NOFOLLOW, so verify via lstat that we did not land on an attacker-placed symlink # or a regular file before we open or scan inside. st = os.lstat(self._paths.readers) if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode): msg = f"{self._paths.readers} exists but is not a directory or is a symlink; refusing to use it" raise RuntimeError(msg) if self._readers_dir_fd is None and _SUPPORTS_DIR_FD: flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | _O_NOFOLLOW self._readers_dir_fd = os.open(self._paths.readers, flags)
def _any_readers(self) -> bool: for _ in self._iter_reader_entries(): return True return False
def _iter_reader_entries(self) -> Generator[tuple[str, bool]]: """ Yield ``(name, dirfd_relative)`` pairs for every live reader marker.
``dirfd_relative`` is ``True`` when *name* should be passed to ``dir_fd=``-aware syscalls; ``False`` when *name* is a full path because dirfd-relative I/O is unavailable on this platform. """ if self._readers_dir_fd is not None: with os.scandir(self._readers_dir_fd) as it: for entry in it: if not _is_housekeeping_name(entry.name): yield entry.name, True return readers_path = Path(self._paths.readers) # pragma: win32 cover with os.scandir(readers_path) as it: # pragma: win32 cover for entry in it: # pragma: win32 cover if not _is_housekeeping_name(entry.name): # pragma: win32 cover yield str(readers_path / entry.name), False # pragma: win32 cover
def _break_stale_readers(self, now: float) -> None: names: list[tuple[str, int | None]] = [] try: for name, dirfd_relative in self._iter_reader_entries(): names.append((name, self._readers_dir_fd if dirfd_relative else None)) except OSError: # pragma: no cover - transient NFS scandir hiccup return for name, fd in names: _break_stale_marker(name, stale_threshold=self.stale_threshold, now=now, dir_fd=fd)
def _refresh_marker(self) -> bool: with self._locks.internal: hold = self._hold if hold is None: # pragma: no cover - race between stop_event.set and join return False marker_name = hold.marker_name token = hold.token dir_fd = self._readers_dir_fd if hold.is_reader else None
read_result = _read_marker(marker_name, dir_fd=dir_fd) if read_result is None: return False info, _mtime = read_result # Token mismatch means another process already evicted our marker and created its own; stop the # thread so it does not touch a stranger's file. if info is None or not hmac.compare_digest(info.token, token): return False try: _touch(marker_name, dir_fd=dir_fd) except FileNotFoundError: # pragma: no cover - race between successful read and touch return False return True
def _reset_after_fork_in_child(self) -> None: # pragma: no cover - fork child not tracked # Replace every lock this instance owns with a fresh one; the inherited locks may still be held # by threads that no longer exist in the child. The readers dirfd and the SoftFileLock state # mutex both get dropped for the same reason — the child re-creates them on its next acquire. self._locks = _Locks( internal=threading.Lock(), transaction=threading.Lock(), state=SoftFileLock(self._paths.state, timeout=-1), ) self._hold = None self._readers_dir_fd = None self._fork_invalidated = True
class _HeartbeatThread(threading.Thread): def __init__( self, refresh: Callable[[], bool], interval: float, stop_event: threading.Event, name: str, ) -> None: super().__init__(name=name, daemon=True) self._refresh = refresh self._interval = interval self._stop_event = stop_event
def run(self) -> None: while not self._stop_event.wait(self._interval): if not self._refresh(): self._stop_event.set() return
def _atomic_create_marker(name: str, token: str, *, dir_fd: int | None = None) -> None: # O_NOFOLLOW blocks the symlink-overwrite attack where an attacker pre-creates the marker path as a # symlink pointing at a victim file. Mode 0o600 keeps the token unreadable to other users. flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY | _O_NOFOLLOW if _SUPPORTS_DIR_FD and dir_fd is not None: fd = os.open(name, flags, 0o600, dir_fd=dir_fd) else: fd = os.open(name, flags, 0o600) try: content = f"{token}\n{os.getpid()}\n{socket.gethostname()}\n".encode("ascii") os.write(fd, content) finally: os.close(fd)
def _read_marker(name: str, *, dir_fd: int | None = None) -> tuple[_MarkerInfo | None, float] | None: # O_NOFOLLOW is defense in depth: we already created this file, but a hostile replacement by symlink # between create and read would be caught here. flags = os.O_RDONLY | _O_NOFOLLOW try: fd = os.open(name, flags, dir_fd=dir_fd) if _SUPPORTS_DIR_FD and dir_fd is not None else os.open(name, flags) except OSError: return None try: try: st = os.fstat(fd) data = os.read(fd, _MAX_MARKER_SIZE + 1) except OSError: # pragma: no cover - fstat/read after a successful open is hard to provoke return None finally: os.close(fd) return _parse_marker_bytes(data), st.st_mtime
def _parse_marker_bytes(data: bytes) -> _MarkerInfo | None: # Trust nothing about attacker-controlled markers; any deviation returns None so callers fall through # to stale cleanup. ``re.match`` caches compiled patterns internally, so the regex is built only once # despite being defined inline. if not data or len(data) > _MAX_MARKER_SIZE: return None try: text = data.decode("ascii") except UnicodeDecodeError: return None match = re.match( r""" \A # start of string (?P<token> [0-9a-f]{32} ) \n # 128-bit hex token (?P<pid> [1-9][0-9]{0,9} ) \n # decimal pid: no leading zero, ≤ 10 digits (?P<hostname> [\x21-\x7e]{1,253}) # printable non-whitespace ASCII (RFC 1123 hostname limit) \n* # tolerate sloppy writers that append extra newlines \Z # end of string """, text, re.VERBOSE, ) if match is None: return None pid = int(match["pid"], 10) if pid > 2**31 - 1: return None return _MarkerInfo(token=match["token"], pid=pid, hostname=match["hostname"])
def _break_stale_marker( # noqa: PLR0911 name: str, *, stale_threshold: float, now: float, dir_fd: int | None = None,) -> bool: # Atomic break pattern: read → rename to unique break-name → re-verify → unlink. The rename gives us a # private name nobody else can touch; if the re-verify sees a newer mtime or a different token, the # legitimate holder's heartbeat fired between read and rename and we must abort (leaving the .break.* # file behind rather than rollback-renaming, because rollback is itself racy). read_result = _read_marker(name, dir_fd=dir_fd) if read_result is None: return False info_before, mtime_before = read_result if now - mtime_before <= stale_threshold: return False if info_before is None: _unlink(name, dir_fd=dir_fd) return True
break_name = f"{name}{_BREAK_SUFFIX}.{os.getpid()}.{secrets.token_hex(16)}" try: if _SUPPORTS_DIR_FD and dir_fd is not None: os.rename(name, break_name, src_dir_fd=dir_fd, dst_dir_fd=dir_fd) else: Path(name).rename(break_name) except OSError: # pragma: no cover - race where the marker vanishes between read and rename return False
read_after = _read_marker(break_name, dir_fd=dir_fd) if read_after is None: # pragma: no cover - race where a peer unlinks the break-name file return False info_after, mtime_after = read_after if info_after is None: # pragma: no cover - content replaced post-rename by a racing peer _unlink(break_name, dir_fd=dir_fd) return True if not hmac.compare_digest(info_before.token, info_after.token): # pragma: no cover - race only return False if mtime_after > mtime_before: # pragma: no cover - heartbeat raced our rename return False _unlink(break_name, dir_fd=dir_fd) return True
def _unlink(name: str, *, dir_fd: int | None = None) -> None: with suppress(FileNotFoundError): if _SUPPORTS_DIR_FD and dir_fd is not None: # Path.unlink has no dir_fd support, so we stay on os.unlink for the dirfd path. os.unlink(name, dir_fd=dir_fd) else: Path(name).unlink()
def _touch(name: str, *, dir_fd: int | None = None) -> None: if _SUPPORTS_DIR_FD and dir_fd is not None: os.utime(name, None, dir_fd=dir_fd) else: os.utime(name, None)
def _file_exists(path: str) -> bool: try: st = os.lstat(path) except FileNotFoundError: return False return stat.S_ISREG(st.st_mode)
def _is_housekeeping_name(name: str) -> bool: return name.startswith(".") or _BREAK_SUFFIX in name
def _reset_all_after_fork() -> None: # pragma: no cover - fork child, not tracked by coverage global _all_instances_lock # noqa: PLW0603 # User-created threading locks do not auto-reset across fork: any lock held by a parent thread stays # locked in the child with no owner to release it. Replace the module-level lock and every instance's # locks with fresh ones; the child is single-threaded at this point so no synchronization is needed. _all_instances_lock = threading.Lock() for instance in list(_all_instances.values()): instance._reset_after_fork_in_child() # noqa: SLF001
def _cleanup_all_instances() -> None: # pragma: no cover - runs from atexit at interpreter shutdown for instance in list(_all_instances.values()): with suppress(Exception): instance.release(force=True)
def _register_hooks() -> None: global _atexit_registered, _fork_registered # noqa: PLW0603 if not _atexit_registered: atexit.register(_cleanup_all_instances) _atexit_registered = True # after_in_child replaces inherited state so the child cannot double-own any lock the parent held. if not _fork_registered and hasattr(os, "register_at_fork"): os.register_at_fork(after_in_child=_reset_all_after_fork) _fork_registered = True
__all__ = [ "SoftReadWriteLock",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116from __future__ import annotations
import osimport sysimport warningsfrom contextlib import suppressfrom errno import EAGAIN, ENOSYS, EWOULDBLOCKfrom pathlib import Pathfrom typing import cast
from ._api import BaseFileLockfrom ._util import ensure_directory_exists
#: a flag to indicate if the fcntl API is availablehas_fcntl = Falseif sys.platform == "win32": # pragma: win32 cover
class UnixFileLock(BaseFileLock): """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
def _acquire(self) -> None: raise NotImplementedError
def _release(self) -> None: raise NotImplementedError
else: # pragma: win32 no cover try: import fcntl
_ = (fcntl.flock, fcntl.LOCK_EX, fcntl.LOCK_NB, fcntl.LOCK_UN) except (ImportError, AttributeError): pass else: has_fcntl = True
class UnixFileLock(BaseFileLock): """ Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems.
Lock file cleanup: Unix and macOS delete the lock file reliably after release, even in multi-threaded scenarios. Unlike Windows, Unix allows unlinking files that other processes have open. """
def _acquire(self) -> None: # noqa: C901, PLR0912 ensure_directory_exists(self.lock_file) open_flags = os.O_RDWR | os.O_TRUNC o_nofollow = getattr(os, "O_NOFOLLOW", None) if o_nofollow is not None: open_flags |= o_nofollow open_flags |= os.O_CREAT open_mode = self._open_mode() try: fd = os.open(self.lock_file, open_flags, open_mode) except FileNotFoundError: # On FUSE/NFS, os.open(O_CREAT) is not atomic: LOOKUP + CREATE can be split, allowing a concurrent # unlink() to delete the file between them. For valid paths, treat ENOENT as transient contention. # For invalid paths (e.g., empty string), re-raise to avoid infinite retry loops. if self.lock_file and Path(self.lock_file).parent.exists(): return raise except PermissionError: # Sticky-bit dirs (e.g. /tmp): O_CREAT fails if the file is owned by another user (#317). # Fall back to opening the existing file without O_CREAT. if not Path(self.lock_file).exists(): raise try: fd = os.open(self.lock_file, open_flags & ~os.O_CREAT, open_mode) except FileNotFoundError: return if self.has_explicit_mode: with suppress(PermissionError): os.fchmod(fd, self._context.mode) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError as exception: os.close(fd) if exception.errno == ENOSYS: with suppress(OSError): Path(self.lock_file).unlink() self._fallback_to_soft_lock() self._acquire() return if exception.errno not in {EAGAIN, EWOULDBLOCK}: raise else: # The file may have been unlinked by a concurrent _release() between our open() and flock(). # A lock on an unlinked inode is useless — discard and let the retry loop start fresh. if os.fstat(fd).st_nlink == 0: os.close(fd) else: self._context.lock_file_fd = fd
def _fallback_to_soft_lock(self) -> None: from ._soft import SoftFileLock # noqa: PLC0415
warnings.warn("flock not supported on this filesystem, falling back to SoftFileLock", stacklevel=2) from .asyncio import AsyncSoftFileLock, BaseAsyncFileLock # noqa: PLC0415
self.__class__ = AsyncSoftFileLock if isinstance(self, BaseAsyncFileLock) else SoftFileLock
def _release(self) -> None: fd = cast("int", self._context.lock_file_fd) self._context.lock_file_fd = None with suppress(OSError): Path(self.lock_file).unlink() fcntl.flock(fd, fcntl.LOCK_UN) with suppress(OSError): # close can raise EIO on FUSE/Docker bind-mount filesystems after unlink os.close(fd)
__all__ = [ "UnixFileLock", "has_fcntl",]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253from __future__ import annotations
import osimport statimport sysfrom errno import EACCES, EISDIRfrom pathlib import Path
def raise_on_not_writable_file(filename: str) -> None: """ Raise an exception if attempting to open the file for writing would fail.
This is done so files that will never be writable can be separated from files that are writable but currently locked.
:param filename: file to check
:raises OSError: as if the file was opened for writing.
""" try: # use stat to do exists + can write to check without race condition file_stat = os.stat(filename) # noqa: PTH116 except OSError: return # swallow does not exist or other errors
if file_stat.st_mtime != 0: # if os.stat returns but modification is zero that's an invalid os.stat - ignore it if not (file_stat.st_mode & stat.S_IWUSR): raise PermissionError(EACCES, "Permission denied", filename)
if stat.S_ISDIR(file_stat.st_mode): if sys.platform == "win32": # pragma: win32 cover # On Windows, this is PermissionError raise PermissionError(EACCES, "Permission denied", filename) else: # pragma: win32 no cover # noqa: RET506 # On linux / macOS, this is IsADirectoryError raise IsADirectoryError(EISDIR, "Is a directory", filename)
def ensure_directory_exists(filename: Path | str) -> None: """ Ensure the directory containing the file exists (create it if necessary).
:param filename: file.
""" Path(filename).parent.mkdir(parents=True, exist_ok=True)
__all__ = [ "ensure_directory_exists", "raise_on_not_writable_file",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111from __future__ import annotations
import osimport sysfrom contextlib import suppressfrom errno import EACCESfrom pathlib import Pathfrom typing import cast
from ._api import BaseFileLockfrom ._util import ensure_directory_exists, raise_on_not_writable_file
if sys.platform == "win32": # pragma: win32 cover import ctypes import msvcrt from ctypes import wintypes
# Windows API constants for reparse point detection FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400 INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF
# Load kernel32.dll _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) _kernel32.GetFileAttributesW.argtypes = [wintypes.LPCWSTR] _kernel32.GetFileAttributesW.restype = wintypes.DWORD
def _is_reparse_point(path: str) -> bool: """ Check if a path is a reparse point (symlink, junction, etc.) on Windows.
:param path: Path to check
:returns: True if path is a reparse point, False otherwise
:raises OSError: If GetFileAttributesW fails for reasons other than file-not-found
""" attrs = _kernel32.GetFileAttributesW(path) if attrs == INVALID_FILE_ATTRIBUTES: # File doesn't exist yet - that's fine, we'll create it err = ctypes.get_last_error() if err == 2: # noqa: PLR2004 # ERROR_FILE_NOT_FOUND return False if err == 3: # noqa: PLR2004 # ERROR_PATH_NOT_FOUND return False # Some other error - let caller handle it return False return bool(attrs & FILE_ATTRIBUTE_REPARSE_POINT)
class WindowsFileLock(BaseFileLock): """ Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems.
Lock file cleanup: Windows attempts to delete the lock file after release, but deletion is not guaranteed in multi-threaded scenarios where another thread holds an open handle. The lock file may persist on disk, which does not affect lock correctness. """
def _acquire(self) -> None: raise_on_not_writable_file(self.lock_file) ensure_directory_exists(self.lock_file)
# Security check: Refuse to open reparse points (symlinks, junctions) # This prevents TOCTOU symlink attacks (CVE-TBD) if _is_reparse_point(self.lock_file): msg = f"Lock file is a reparse point (symlink/junction): {self.lock_file}" raise OSError(msg)
flags = ( os.O_RDWR # open for read and write | os.O_CREAT # create file if not exists ) try: fd = os.open(self.lock_file, flags, self._open_mode()) except OSError as exception: if exception.errno != EACCES: # has no access to this lock raise else: try: msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) except OSError as exception: os.close(fd) # close file first if exception.errno != EACCES: # file is already locked raise else: self._context.lock_file_fd = fd
def _release(self) -> None: fd = cast("int", self._context.lock_file_fd) self._context.lock_file_fd = None msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) os.close(fd)
with suppress(OSError): Path(self.lock_file).unlink()
else: # pragma: win32 no cover
class WindowsFileLock(BaseFileLock): """Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems."""
def _acquire(self) -> None: raise NotImplementedError
def _release(self) -> None: raise NotImplementedError
__all__ = [ "WindowsFileLock",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385"""An asyncio-based implementation of the file lock."""
from __future__ import annotations
import asyncioimport contextlibimport loggingimport osimport timefrom dataclasses import dataclassfrom inspect import iscoroutinefunctionfrom threading import localfrom typing import TYPE_CHECKING, Any, NoReturn, TypeVar
from ._api import _UNSET_FILE_MODE, BaseFileLock, FileLockContext, FileLockMetafrom ._error import Timeoutfrom ._soft import SoftFileLockfrom ._unix import UnixFileLockfrom ._windows import WindowsFileLock
if TYPE_CHECKING: import sys from collections.abc import Callable from concurrent import futures from types import TracebackType
if sys.version_info >= (3, 11): # pragma: no cover (py311+) from typing import Self else: # pragma: no cover (<py311) from typing_extensions import Self
_LOGGER = logging.getLogger("filelock")
@dataclassclass AsyncFileLockContext(FileLockContext): """A dataclass which holds the context for a ``BaseAsyncFileLock`` object."""
#: Whether run in executor run_in_executor: bool = True
#: The executor executor: futures.Executor | None = None
#: The loop loop: asyncio.AbstractEventLoop | None = None
class AsyncThreadLocalFileContext(AsyncFileLockContext, local): """A thread local version of the ``FileLockContext`` class."""
class AsyncAcquireReturnProxy: """A context-aware object that will release the lock file when exiting."""
def __init__(self, lock: BaseAsyncFileLock) -> None: # noqa: D107 self.lock = lock
async def __aenter__(self) -> BaseAsyncFileLock: # noqa: D105 return self.lock
async def __aexit__( # noqa: D105 self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: await self.lock.release()
_AT = TypeVar("_AT", bound="BaseAsyncFileLock")
class AsyncFileLockMeta(FileLockMeta): def __call__( # ty: ignore[invalid-method-override] # noqa: PLR0913 cls: type[_AT], # noqa: N805 lock_file: str | os.PathLike[str], timeout: float = -1, mode: int = _UNSET_FILE_MODE, thread_local: bool = False, # noqa: FBT001, FBT002 *, blocking: bool = True, is_singleton: bool = False, poll_interval: float = 0.05, lifetime: float | None = None, loop: asyncio.AbstractEventLoop | None = None, run_in_executor: bool = True, executor: futures.Executor | None = None, ) -> _AT: if thread_local and run_in_executor: msg = "run_in_executor is not supported when thread_local is True" raise ValueError(msg) return super().__call__( lock_file=lock_file, timeout=timeout, mode=mode, thread_local=thread_local, blocking=blocking, is_singleton=is_singleton, poll_interval=poll_interval, lifetime=lifetime, loop=loop, run_in_executor=run_in_executor, executor=executor, )
class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta): """ Base class for asynchronous file locks.
.. versionadded:: 3.15.0
"""
def __init__( # noqa: PLR0913 self, lock_file: str | os.PathLike[str], timeout: float = -1, mode: int = _UNSET_FILE_MODE, thread_local: bool = False, # noqa: FBT001, FBT002 *, blocking: bool = True, is_singleton: bool = False, poll_interval: float = 0.05, lifetime: float | None = None, loop: asyncio.AbstractEventLoop | None = None, run_in_executor: bool = True, executor: futures.Executor | None = None, ) -> None: """ Create a new lock object.
:param lock_file: path to the file :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in the acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it to a negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock. :param mode: file permissions for the lockfile. When not specified, the OS controls permissions via umask and default ACLs, preserving POSIX default ACL inheritance in shared directories. :param thread_local: Whether this object's internal context should be thread local or not. If this is set to ``False`` then the lock will be reentrant across threads. :param blocking: whether the lock should be blocking or not :param is_singleton: If this is set to ``True`` then only one instance of this class will be created per lock file. This is useful if you want to use the lock object for reentrant locking without needing to pass the same object around. :param poll_interval: default interval for polling the lock file, in seconds. It will be used as fallback value in the acquire method, if no poll_interval value (``None``) is given. :param lifetime: maximum time in seconds a lock can be held before it is considered expired. When set, a waiting process will break a lock whose file modification time is older than ``lifetime`` seconds. ``None`` (the default) means locks never expire. :param loop: The event loop to use. If not specified, the running event loop will be used. :param run_in_executor: If this is set to ``True`` then the lock will be acquired in an executor. :param executor: The executor to use. If not specified, the default executor will be used.
""" self._is_thread_local = thread_local self._is_singleton = is_singleton
# Create the context. Note that external code should not work with the context directly and should instead use # properties of this class. kwargs: dict[str, Any] = { "lock_file": os.fspath(lock_file), "timeout": timeout, "mode": mode, "blocking": blocking, "poll_interval": poll_interval, "lifetime": lifetime, "loop": loop, "run_in_executor": run_in_executor, "executor": executor, } self._context: AsyncFileLockContext = (AsyncThreadLocalFileContext if thread_local else AsyncFileLockContext)( **kwargs )
@property def run_in_executor(self) -> bool: """:returns: whether run in executor.""" return self._context.run_in_executor
@property def executor(self) -> futures.Executor | None: """:returns: the executor.""" return self._context.executor
@executor.setter def executor(self, value: futures.Executor | None) -> None: # pragma: no cover """ Change the executor.
:param futures.Executor | None value: the new executor or ``None``
""" self._context.executor = value
@property def loop(self) -> asyncio.AbstractEventLoop | None: """:returns: the event loop.""" return self._context.loop
async def acquire( # ty: ignore[invalid-method-override] self, timeout: float | None = None, poll_interval: float | None = None, *, blocking: bool | None = None, cancel_check: Callable[[], bool] | None = None, ) -> AsyncAcquireReturnProxy: """ Try to acquire the file lock.
:param timeout: maximum wait time for acquiring the lock, ``None`` means use the default :attr:`~BaseFileLock.timeout` is and if ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired :param poll_interval: interval of trying to acquire the lock file, ``None`` means use the default :attr:`~BaseFileLock.poll_interval` :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired. :param cancel_check: a callable returning ``True`` when the acquisition should be canceled. Checked on each poll iteration. When triggered, raises :class:`~Timeout` just like an expired timeout.
:returns: a context object that will unlock the file when the context is exited
:raises Timeout: if fails to acquire lock within the timeout period
.. code-block:: python
# You can use this method in the context manager (recommended) with lock.acquire(): pass
# Or use an equivalent try-finally construct: lock.acquire() try: pass finally: lock.release()
""" # Use the default timeout, if no timeout is provided. if timeout is None: timeout = self._context.timeout
if blocking is None: blocking = self._context.blocking
if poll_interval is None: poll_interval = self._context.poll_interval
# Increment the number right at the beginning. We can still undo it, if something fails. self._context.lock_counter += 1
lock_id = id(self) lock_filename = self.lock_file start_time = time.perf_counter() try: while True: if not self.is_locked: self._try_break_expired_lock() _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename) await self._run_internal_method(self._acquire) if self.is_locked: _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename) break if self._check_give_up( lock_id, lock_filename, blocking=blocking, cancel_check=cancel_check, timeout=timeout, start_time=start_time, ): raise Timeout(lock_filename) # noqa: TRY301 msg = "Lock %s not acquired on %s, waiting %s seconds ..." _LOGGER.debug(msg, lock_id, lock_filename, poll_interval) await asyncio.sleep(poll_interval) except BaseException: # Something did go wrong, so decrement the counter. self._context.lock_counter = max(0, self._context.lock_counter - 1) raise return AsyncAcquireReturnProxy(lock=self)
async def release(self, force: bool = False) -> None: # ty: ignore[invalid-method-override] # noqa: FBT001, FBT002 """ Release the file lock. The lock is only completely released when the lock counter reaches 0. The lock file itself is not automatically deleted.
:param force: If true, the lock counter is ignored and the lock is released in every case.
""" if self.is_locked: self._context.lock_counter -= 1
if self._context.lock_counter == 0 or force: lock_id, lock_filename = id(self), self.lock_file
_LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename) await self._run_internal_method(self._release) self._context.lock_counter = 0 _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename)
async def _run_internal_method(self, method: Callable[[], Any]) -> None: if iscoroutinefunction(method): await method() elif self.run_in_executor: await asyncio.get_running_loop().run_in_executor(self.executor, method) else: method()
def __enter__(self) -> NoReturn: """Sync context manager entry is not supported because lock acquisition is a coroutine.""" msg = "Use `async with` — acquire/release are coroutines and cannot be awaited in a sync context manager." raise NotImplementedError(msg)
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: object, ) -> None: """Sync context manager exit is not supported because lock release is a coroutine.""" msg = "Use `async with` — acquire/release are coroutines and cannot be awaited in a sync context manager." raise NotImplementedError(msg)
async def __aenter__(self) -> Self: """ Acquire the lock.
:returns: the lock object
""" await self.acquire() return self
async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: """ Release the lock.
:param exc_type: the exception type if raised :param exc_value: the exception value if raised :param traceback: the exception traceback if raised
""" await self.release()
def __del__(self) -> None: """Release on deletion — safe to call during GC even when no event loop is running.""" with contextlib.suppress(Exception): try: loop = asyncio.get_running_loop() except RuntimeError: # No running loop — try stored loop or create one loop = self._context.loop if self._context.loop and not self._context.loop.is_closed() else None if loop is None: return if not loop.is_running(): # pragma: no cover loop.run_until_complete(self.release(force=True)) else: loop.create_task(self.release(force=True))
class AsyncSoftFileLock(SoftFileLock, BaseAsyncFileLock): """Simply watches the existence of the lock file."""
class AsyncUnixFileLock(UnixFileLock, BaseAsyncFileLock): """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
class AsyncWindowsFileLock(WindowsFileLock, BaseAsyncFileLock): """Uses the :func:`msvcrt.locking` to hard lock the lock file on windows systems."""
__all__ = [ "AsyncAcquireReturnProxy", "AsyncSoftFileLock", "AsyncUnixFileLock", "AsyncWindowsFileLock", "BaseAsyncFileLock",].cache/pip/http-v2/3/4/e/4/e/34e4ed9f6da78ec378e04be04de734c69a68c889dbef86cb0f5f498aAdded
.cache/pip/http-v2/3/4/e/4/e/34e4ed9f6da78ec378e04be04de734c69a68c889dbef86cb0f5f498a.bodyAdded
.cache/pip/http-v2/3/5/a/0/6/35a0615e0411edd59492c90e8f5cd0a1a0554d6f7d1dec5be2b30560Added
.cache/pip/http-v2/3/5/a/0/6/35a0615e0411edd59492c90e8f5cd0a1a0554d6f7d1dec5be2b30560.bodyAdded+97
.cache/pip/http-v2/3/7/c/5/1/37c518ffee828550acec5a0fd158a5f1d852928eea13df9d077b428bAdded
.cache/pip/http-v2/3/7/c/5/1/37c518ffee828550acec5a0fd158a5f1d852928eea13df9d077b428b.bodyAdded
.cache/pip/http-v2/3/8/6/0/e/3860e4de9ae53c79d2fd61419e9049df314ccc8b640782c02c6e2e2dAdded
.cache/pip/http-v2/3/8/6/0/e/3860e4de9ae53c79d2fd61419e9049df314ccc8b640782c02c6e2e2d.bodyAdded
.cache/pip/http-v2/3/8/9/2/7/389270eb64d5d655add63491064e7e833611004a96c2fb8b19caa5fbAdded
.cache/pip/http-v2/3/8/9/2/7/389270eb64d5d655add63491064e7e833611004a96c2fb8b19caa5fb.bodyAdded+321
.cache/pip/http-v2/3/8/c/c/8/38cc8209283ecb2d228ea8086bb74fbdc5d4872485c51a94fdb9c6cbAdded
.cache/pip/http-v2/4/4/a/d/5/44ad51ab4fe732177892254938ca19df59a19add805fe17b3b22c658Added
.cache/pip/http-v2/4/4/a/d/5/44ad51ab4fe732177892254938ca19df59a19add805fe17b3b22c658.bodyAdded+1595
.cache/pip/http-v2/4/6/5/f/3/465f3fcecb7ed980c1b4d56b4f1ac8b2ae4685d32a696bbd51a25fb9Added
.cache/pip/http-v2/4/6/5/f/3/465f3fcecb7ed980c1b4d56b4f1ac8b2ae4685d32a696bbd51a25fb9.bodyAdded+329
.cache/pip/http-v2/4/a/5/b/6/4a5b6f0d76201de4cfd4884f5e95617a1848cf81c8357be4d12cbf6aAdded
.cache/pip/http-v2/4/a/5/b/6/4a5b6f0d76201de4cfd4884f5e95617a1848cf81c8357be4d12cbf6a.bodyAdded+86
.cache/pip/http-v2/4/d/c/8/d/4dc8d567db4bc55c0684404c85a6b4572f87a99306be24cab65fbfaeAdded
.cache/pip/http-v2/4/d/c/8/d/4dc8d567db4bc55c0684404c85a6b4572f87a99306be24cab65fbfae.bodyAdded
.cache/pip/http-v2/4/f/3/2/1/4f3214a3fad8d38cb17e7de04e5671458da4f4634932269127d53af7Added
.cache/pip/http-v2/9/b/5/1/6/9b51619e20a708f99372afefd7dbe20a1b5e42ae213f02bf27267976Added
.cache/pip/http-v2/c/3/a/e/f/c3aefa2552222433000010e47def822725a77e3cf762f96a15f09d26Added
.cache/pip/http-v2/c/3/a/e/f/c3aefa2552222433000010e47def822725a77e3cf762f96a15f09d26.bodyAdded+907
.cache/pip/http-v2/c/6/3/0/6/c6306d205b48faecb62eb823053e850df036f38e59b11523829f5c31Added
.cache/pip/http-v2/c/6/3/0/6/c6306d205b48faecb62eb823053e850df036f38e59b11523829f5c31.bodyAdded
.cache/pip/http-v2/c/8/4/4/6/c84464fe37be1d534151bcdb9cc17e882f3b79853f43ffdb6425f333Added
.cache/pip/http-v2/c/8/4/4/6/c84464fe37be1d534151bcdb9cc17e882f3b79853f43ffdb6425f333.bodyAdded+1086
.cache/pip/http-v2/c/c/c/b/4/cccb41730ba9dcdb4cb7127715ba43b53bfd809d6ff652fe215567a3Added
.cache/pip/http-v2/c/c/c/b/4/cccb41730ba9dcdb4cb7127715ba43b53bfd809d6ff652fe215567a3.bodyAdded+300
.cache/pip/http-v2/c/d/5/d/e/cd5de44b899cbe1869765c21b55cffc53c0c0ffa9d3c6f1fd40a42a2Added
.cache/pip/http-v2/f/9/5/d/2/f95d294c2281f9705ab34177ee4732e524880c56ef894e620cf4cb95Added
.cache/pip/http-v2/f/9/5/d/2/f95d294c2281f9705ab34177ee4732e524880c56ef894e620cf4cb95.bodyAdded
.cache/pip/http-v2/f/c/6/8/7/fc687abc6120c7bc7cfd867fe3788604e9f8e9dcf17e51396d803e25Added
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock-3.29.0.dist-info/METADATAAdded+38
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock-3.29.0.dist-info/RECORDAdded+19
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock-3.29.0.dist-info/WHEELAdded+4
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock-3.29.0.dist-info/licenses/LICENSEAdded+21
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/__init__.pyAdded+93
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_api.pyAdded+582
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_async_read_write.pyAdded+207
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_error.pyAdded+30
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_read_write.pyAdded+364
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_soft.pyAdded+214
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_soft_rw/_async.pyAdded+213
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_soft_rw/_sync.pyAdded+847
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_unix.pyAdded+116
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_util.pyAdded+53
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/_windows.pyAdded+111
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/asyncio.pyAdded+385
.cache/uv/archive-v0/-y3nSpGgh2lg0PkmpCImR/filelock/py.typedAdded