python3-defaults-3.6.7/0000775000000000000000000000000013364125767011646 5ustar python3-defaults-3.6.7/.gitignore0000664000000000000000000000104513305601050013611 0ustar debian/*.debhelper* debian/*.substvars debian/files debian/python3-minimal.postinst debian/python3.postinst debian/python3.postrm debian/python3.preinst debian/2to3 debian/idle debian/idle3 debian/libpython3-all-dbg debian/libpython3-all-dev debian/libpython3-dbg debian/libpython3-dev debian/libpython3-stdlib debian/python3 debian/python3-all debian/python3-all-dbg debian/python3-all-dev debian/python3-dbg debian/python3-dev debian/python3-doc debian/python3-examples debian/python3-minimal debian/python3-venv py3clean.1 py3compile.1 stamp-* python3-defaults-3.6.7/Makefile0000664000000000000000000000341613305601050013265 0ustar #!/usr/bin/make -f INSTALL ?= install PREFIX ?= /usr/local MANPAGES ?= py3compile.1 py3clean.1 VERSION=$(shell dpkg-parsechangelog | sed -rne 's,^Version: (.+),\1,p') clean: find . -name '*.py[co]' -delete find . -name __pycache__ -type d | xargs rm -rf rm -f .coverage $(MANPAGES) install-dev: $(INSTALL) -m 755 -d $(DESTDIR)$(PREFIX)/bin \ $(DESTDIR)$(PREFIX)/share/python3/runtime.d $(INSTALL) -m 755 runtime.d/* $(DESTDIR)$(PREFIX)/share/python3/runtime.d/ install-runtime: $(INSTALL) -m 755 -d $(DESTDIR)$(PREFIX)/share/python3/debpython $(DESTDIR)$(PREFIX)/bin $(INSTALL) -m 644 debpython/*.py $(DESTDIR)$(PREFIX)/share/python3/debpython/ $(INSTALL) -m 755 py3compile $(DESTDIR)$(PREFIX)/bin/ sed -i -e 's/DEVELV/$(VERSION)/' $(DESTDIR)$(PREFIX)/bin/py3compile $(INSTALL) -m 755 py3clean $(DESTDIR)$(PREFIX)/bin/ sed -i -e 's/DEVELV/$(VERSION)/' $(DESTDIR)$(PREFIX)/bin/py3clean install: install-dev install-runtime %.1: %.rst rst2man $< > $@ manpages: $(MANPAGES) pdebuild: pdebuild --debbuildopts -I # TESTS tests: nosetests3 --with-doctest --with-coverage check_versions: @PYTHONPATH=. set -e; \ DEFAULT=`python3 -c 'import debpython.version as v; print(v.vrepr(v.DEFAULT))'`;\ SUPPORTED=`python3 -c 'import debpython.version as v; print(" ".join(sorted(v.vrepr(v.SUPPORTED))))'`;\ DEB_DEFAULT=`sed -rn 's,^default-version = python([0.9.]*),\1,p' debian/debian_defaults`;\ DEB_SUPPORTED=`sed -rn 's|^supported-versions = (.*)|\1|p' debian/debian_defaults | sed 's/python//g;s/,//g'`;\ [ "$$DEFAULT" = "$$DEB_DEFAULT" ] || \ (echo 'Please update DEFAULT in debpython/version.py' >/dev/stderr; false);\ [ "$$SUPPORTED" = "$$DEB_SUPPORTED" ] || \ (echo 'Please update SUPPORTED in debpython/version.py' >/dev/stderr; false) .PHONY: clean tests test% check_versions python3-defaults-3.6.7/README.derivatives0000664000000000000000000000077613305601050015037 0ustar How to change a list of supported Python versions? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Open debian/debian_defaults file and change `supported-versions` variable, separating multiple values by comma * Open debian/control.in file and edit python3-all, python3-all-dev and python3-all-dbg's Depends line (add or remove pythonX.Y packages) How to change default Python version? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Open debian/debian_defaults file and change `default-version` variable python3-defaults-3.6.7/debian/0000775000000000000000000000000013364322304013052 5ustar python3-defaults-3.6.7/debian/2to3.10000664000000000000000000000201613305601050013713 0ustar .\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.40.4. .TH 2TO3-3.3 "1" "January 2012" "2to3-3.3 3.3" "User Commands" .SH NAME 2to3-3.3 \- Python2 to Python3 converter .SH SYNOPSIS .B 2to3 [\fIoptions\fR] \fIfile|dir \fR... .SH OPTIONS .TP \fB\-h\fR, \fB\-\-help\fR show this help message and exit .TP \fB\-d\fR, \fB\-\-doctests_only\fR Fix up doctests only .TP \fB\-f\fR FIX, \fB\-\-fix\fR=\fIFIX\fR Each FIX specifies a transformation; default: all .TP \fB\-j\fR PROCESSES, \fB\-\-processes\fR=\fIPROCESSES\fR Run 2to3 concurrently .TP \fB\-x\fR NOFIX, \fB\-\-nofix\fR=\fINOFIX\fR Prevent a transformation from being run .TP \fB\-l\fR, \fB\-\-list\-fixes\fR List available transformations .TP \fB\-p\fR, \fB\-\-print\-function\fR Modify the grammar so that print() is a function .TP \fB\-v\fR, \fB\-\-verbose\fR More verbose logging .TP \fB\-\-no\-diffs\fR Don't show diffs of the refactoring .TP \fB\-w\fR, \fB\-\-write\fR Write back modified files .TP \fB\-n\fR, \fB\-\-nobackups\fR Don't write backups for modified files python3-defaults-3.6.7/debian/2to3.py0000775000000000000000000000013613305601050014207 0ustar #! /usr/bin/python3 import sys from lib2to3.main import main sys.exit(main("lib2to3.fixes")) python3-defaults-3.6.7/debian/README.Debian0000664000000000000000000000071613305601050015110 0ustar More documentation and README's for this package can be found in the directory /usr/share/doc/python3.6/ The upstream documentation can be found after installation of the python-doc package in the directory /usr/share/doc/python3/html A draft of the "Debian Python Policy", mostly needed for Debian package maintainers can be found in /usr/share/doc/python Sometime it will be moved to /usr/share/doc/debian-policy in the debian-policy package. python3-defaults-3.6.7/debian/changelog0000664000000000000000000014776313364322304014746 0ustar python3-defaults (3.6.7-1~18.04) bionic-proposed; urgency=medium * SRU: LP: #1799206. * Drop python3.7 as a supported python3 version for the bionic SRU. -- Matthias Klose Thu, 25 Oct 2018 13:11:00 +0200 python3-defaults (3.6.7-1) unstable; urgency=high * Really ship the policy in the python3 package, and update from the last version found in the python package. Closes: #910113. * Bump version to 3.6.7. -- Matthias Klose Sun, 21 Oct 2018 11:21:31 +0200 python3-defaults (3.6.6-1) unstable; urgency=medium [ Matthias Klose ] * Fix the idle desktop file. Closes: #901096. * Install the policy files in the python3 package. Closes: #901486. * python3-minimal: Pre-Depend on python3.6-minimal. Closes: #901001. * Bump version to 3.6.6. [ Scott Kitterman ] * Remove myself from uploaders -- Matthias Klose Wed, 27 Jun 2018 18:18:20 +0200 python3-defaults (3.6.5-3ubuntu1) bionic; urgency=medium * Switch python3.x-minimal to a pre-dependency for python3-minimal so that release upgrades will be more smooth. (LP: #1768379) -- Brian Murray Thu, 21 Jun 2018 14:52:37 -0700 python3-defaults (3.6.5-5) experimental; urgency=medium * Fix typo in the defaults file. Closes: #900937, #900949. -- Matthias Klose Thu, 07 Jun 2018 17:57:53 +0200 python3-defaults (3.6.5-4) experimental; urgency=medium * Update Vcs attributes. * Add Python 3.7 to the list of supported Python3 versions. -- Matthias Klose Wed, 06 Jun 2018 18:26:50 +0200 python3-defaults (3.6.5-3) unstable; urgency=medium * Update valgrind support file. LP: #1513364. * debian/control.in (Michael Vogt): - add Cnf-Visible-Pkgname hint to ensure command-not-found recommends installing "python3" instead of "python3-minimal" when it is missing. -- Matthias Klose Tue, 10 Apr 2018 11:48:03 +0200 python3-defaults (3.6.5-2) unstable; urgency=medium * Distinguish between python3.6 and python3-stdlib-extensions versions. Closes: #894168. * python3-venv: Depend on python3-distutils. -- Matthias Klose Mon, 02 Apr 2018 07:06:32 +0200 python3-defaults (3.6.5-1) unstable; urgency=medium [ Matthias Klose ] * Bump version to 3.6.5. [ Michael Vogt ] * debian/control.in: LP: #1752415 - add "XB-Cnf-Extra-Commands: python" to ensure command-not-found outputs the python3 package when searching for "python" - add XB-Cnf-Priority-Bonus to ensure python3 is listed on the top when typing "python" -- Matthias Klose Sat, 31 Mar 2018 16:26:32 +0800 python3-defaults (3.6.5~rc1-1) unstable; urgency=medium * Bump version to 3.6.5~rc1. * Remove dh-python dependency from python3. * Add dh-python and python3-distutils dependencies to python3-all and python3-dev. -- Matthias Klose Sun, 25 Mar 2018 19:05:26 +0800 python3-defaults (3.6.4-1) unstable; urgency=medium * Bump version to 3.6.4. * 2to3: Depend on python3-lib2to3 and provide the 2to3 launcher. -- Matthias Klose Fri, 29 Dec 2017 23:53:39 +0100 python3-defaults (3.6.4~rc1-2) unstable; urgency=medium * 2to3: Fix breaks/replaces relation with python. Closes: #884418. -- Matthias Klose Fri, 15 Dec 2017 08:24:00 +0100 python3-defaults (3.6.4~rc1-1) unstable; urgency=medium * Bump version to 3.6.4~rc1. * Stop using priority extra for the -dbg packages. * Build a 2to3 package. -- Matthias Klose Wed, 13 Dec 2017 23:52:01 +0100 python3-defaults (3.6.3-2) unstable; urgency=medium * Remove python3.5 as a supported Python3 version. -- Matthias Klose Thu, 26 Oct 2017 21:09:05 +0200 python3-defaults (3.6.3-1) unstable; urgency=medium * Bump version to 3.6.3. * Update more references from 3.5 to 3.6. * Rename the idle3 package to idle, keep a transitional idle3 package. * Fix idle script to run with Python3. * Bump standards version to 4.1.1. -- Matthias Klose Tue, 10 Oct 2017 08:36:04 +0200 python3-defaults (3.6.2-1) experimental; urgency=medium * Default python3 version to 3.6. * Bump standards version to 4.1.0. * Change policy format from debiandoc SGML to DocBook/XML (W. Martin Borgert). Closes: #871526, #872581. * Fix some invalid escape sequences that make autopkgtests fail by causing warnings on stderr (Michael Hudson-Doyle). * python3-doc, python3-examples: Mark M-A: foreign. -- Matthias Klose Mon, 18 Sep 2017 19:52:28 +0200 python3-defaults (3.5.3-3) unstable; urgency=medium * Upload to unstable * Update python3 version number in debian/README.Debian (Closes: #826565) * Add debian/watch, thanks to Taylor Kline for the patch (Closes: #850789) * No VCS cruft in the tarball this time (Closes: #854974) * Bump standards version to 4.0.0 without further change * Delete ancient Breaks/Replaces for idle3 and python3-minimal -- Scott Kitterman Wed, 28 Jun 2017 23:07:12 -0400 python3-defaults (3.5.3-2) experimental; urgency=medium * Add python3.6 to supported python3 versions for experimental -- Scott Kitterman Fri, 16 Jun 2017 22:09:52 -0400 python3-defaults (3.5.3-1) unstable; urgency=medium * Bump version to 3.5.3. -- Matthias Klose Fri, 20 Jan 2017 11:03:28 +0100 python3-defaults (3.5.1-4) unstable; urgency=medium * Bump standards version. * Rebuild to pick up the GNU triplet change on i386 archs. Addresses: #826128. -- Matthias Klose Fri, 03 Jun 2016 01:34:07 +0200 python3-defaults (3.5.1-3) unstable; urgency=medium * Drop build dependency on python3.4. * Bump standards and debhelper versions. -- Matthias Klose Mon, 21 Mar 2016 12:58:34 +0100 python3-defaults (3.5.1-2) unstable; urgency=medium * Drop Python 3.4 as a supported python3 version. -- Matthias Klose Mon, 22 Feb 2016 12:53:25 +0100 python3-defaults (3.5.1-1) unstable; urgency=medium * Upload to unstable [ Scott Kitterman ] * Drop redundant supported/default version definitions in debpython/ version.py [ Matthias Klose ] * Bump version to 3.5.1. * Stop shipping menu files. -- Scott Kitterman Mon, 11 Jan 2016 11:35:49 -0500 python3-defaults (3.5.0-2) experimental; urgency=medium * Update py3versions to list versions in a consistent order: default listed last and non-default listed first in ascending order (Closes: #801376) -- Scott Kitterman Sat, 10 Oct 2015 21:21:44 -0400 python3-defaults (3.5.0-1) experimental; urgency=medium * Set python3.5 as the default python3 for testing in experimental -- Scott Kitterman Mon, 05 Oct 2015 16:44:27 -0400 python3-defaults (3.4.3-7) unstable; urgency=medium * Update py3versions to list versions in a consistent order: default listed last and non-default listed first in ascending order (Closes: #801376) -- Scott Kitterman Sun, 11 Oct 2015 12:50:01 -0400 python3-defaults (3.4.3-6) unstable; urgency=medium * Upload to unstable - Adds python3.5 as a supported python3 version in unstable * Update idle3 desktop file to better support use from file managers such as nautilus (Closes: #796125) - Thanks to Pat Hooper for the patch -- Scott Kitterman Thu, 24 Sep 2015 21:47:47 -0400 python3-defaults (3.4.3-5) experimental; urgency=medium * Readd python3.5 as a supported version for experimental -- Scott Kitterman Sat, 27 Jun 2015 18:50:26 -0400 python3-defaults (3.4.3-4) unstable; urgency=medium * Upload to unstable [ Matthias Klose ] * Update README for python 3.4. Closes: #772545. [ Scott Kitterman ] * Drop python3.5 as a supported version for upload to unstable -- Scott Kitterman Sat, 27 Jun 2015 18:47:18 -0400 python3-defaults (3.4.3-2) experimental; urgency=medium * Add python3.5 as a supported Python version. -- Matthias Klose Wed, 03 Jun 2015 01:41:07 +0200 python3-defaults (3.4.3-1) experimental; urgency=medium * Bump version to 3.4.3. * Make python3-minimal a pre-dependency for python3. -- Matthias Klose Sat, 28 Feb 2015 17:05:58 +0100 python3-defaults (3.4.2-2) unstable; urgency=medium * py3clean: remove pyc files generated from files with dot in its name (workaraunds http://bugs.python.org/issue22966) -- Piotr Ożarowski Sat, 29 Nov 2014 18:14:17 +0100 python3-defaults (3.4.2-1) unstable; urgency=medium [ Scott Kitterman ] * Drop unused B-D-I on libhtml-tree-perl * Use dpkg-vendor instead of lsb-release to determine distribution. [ Matthias Klose ] * Bump version to 3.4.2. * Bump standards version to 3.9.6. * Build-depend on python3.4 and dpkg-dev versions to consistently generate the i586-* symlinks. Closes: #762980. -- Matthias Klose Wed, 08 Oct 2014 12:52:49 +0200 python3-defaults (3.4.1-1) unstable; urgency=medium * Bump version to 3.4.1. * Drop python3.3 as a supported python version. * Build a python3-venv binary package. * Fix lintian warnings. * py3versions: Ignore blank lines before the source section in the control file. Closes: #739935. -- Matthias Klose Wed, 04 Jun 2014 12:39:42 +0200 python3-defaults (3.4.1~rc1-1) unstable; urgency=medium * Upload to unstable * Bump version to 3.4.1~rc1 -- Scott Kitterman Tue, 27 May 2014 22:49:41 -0400 python3-defaults (3.4~rc1-1) experimental; urgency=medium * Default to python3.4. -- Matthias Klose Wed, 12 Feb 2014 13:03:28 +0100 python3-defaults (3.3.4-1) unstable; urgency=medium * Bump version to 3.3.4. -- Matthias Klose Wed, 12 Feb 2014 11:15:40 +0100 python3-defaults (3.3.3-1) experimental; urgency=low * Add python3.4 as a supported python version. -- Matthias Klose Thu, 26 Dec 2013 00:39:55 +0100 python3-defaults (3.3.2-17) unstable; urgency=low * Add Multi-Arch: allowed for python3-all-dev. -- Matthias Klose Wed, 18 Sep 2013 15:46:08 +0200 python3-defaults (3.3.2-16) unstable; urgency=low * Restore :any relationship for python3-minimal build-dep now that it is supported on the buildds -- Scott Kitterman Sat, 07 Sep 2013 17:11:07 -0400 python3-defaults (3.3.2-15) unstable; urgency=low * Drop non-existing :any from python3-minimal build-dep. -- Scott Kitterman Sun, 18 Aug 2013 11:38:29 -0400 python3-defaults (3.3.2-14) unstable; urgency=low * Add python3.1 and python3.2 to unsupported-versions * Build-depend on python3-minimal:any instead of python since that's what's used during the build now * Build-depend on python3-docutils instead of python-docutils * Add Multi-Arch: allowed for python3-all and python3-all-dbg * Add libpython3-dbg to python3-dbg depends * Add libpython3-dev to python3-dev depends * Use generated depends in control.in for libpython3-stdlib as with other binaries * Set UPSTRVER for Ubuntu in debian/rules so correct results are produced in both Debian and Ubuntu -- Scott Kitterman Sun, 18 Aug 2013 06:22:22 -0400 python3-defaults (3.3.2-13) unstable; urgency=low * Bump python3-minimal Breaks/Replaces python3 versions to 3.3.2-13~ to account for files moved in -4 and later (Closes: #718734) * Fix broken libpython3-all-dbg symlink -- Scott Kitterman Mon, 05 Aug 2013 02:25:13 -0400 python3-defaults (3.3.2-12) unstable; urgency=low * Re-upload with a version newer than the one in experimental. * Build libpython3-all-{dev,dbg} and libpython3-stdlib packages. * Move debiandoc-sgml and lsb-release from Build-Depends-Indep to Build-Depends. -- Matthias Klose Sat, 03 Aug 2013 09:52:26 +0200 python3-defaults (3.3.2-5) unstable; urgency=low * Drop python3.2 from supported python3 versions -- Scott Kitterman Fri, 02 Aug 2013 22:58:22 -0400 python3-defaults (3.3.2-4) unstable; urgency=low * Upload to unstable * Remove /usr/share/python3/debpython/__pycache__ in python3-minimal's prerm * Change source format back to 1.0 (native) -- Piotr Ożarowski Thu, 01 Aug 2013 21:41:34 +0200 python3-defaults (3.3.2-11) experimental; urgency=low * Make datetime module optional in debpython (it's not available in python3.X-minimal, closes: #717232) -- Piotr Ożarowski Thu, 18 Jul 2013 22:50:17 +0200 python3-defaults (3.3.2-10) experimental; urgency=low [ Matthias Klose ] * Move py3compile and py3clean back to the python3-minimal package. [ Piotr Ożarowski ] * Remove pybuild and dh_python3, dh-python source package provides it now * Add dh-python dependency in python3 package (to make sure dh_python3 is installed) * Bump Standards-Version to 3.9.4 -- Piotr Ożarowski Mon, 15 Jul 2013 23:48:04 +0200 python3-defaults (3.3.2-3) unstable; urgency=low * Bump python3-minimal Breaks/Replaces python3 versions to 3.3.2-1~ to account for files moved in -2 (closes: #717373) -- Scott Kitterman Sun, 21 Jul 2013 09:30:39 -0400 python3-defaults (3.3.2-2) unstable; urgency=low [ Matthias Klose ] * Build dependency packages as architecture dependent packages. * Make python3, python3-{minimal,dev,dbg} Multi-Arch: allowed. * Don't use the `u' abi flag when defaulting to 3.3. * Build Multi-Arch: same packages libpython3-{dev,dbg} packages providing $(DEB_HOST_MULTIARCH)-python3-config symlinks. [ Piotr Ożarowski ] * Move python-docutils to Build-Depends (python3 package is now arch:any) [ Dmitry Shachnev ] * Include architecture.mk in debian/rules instead of defining DEB_HOST_* manually. [ Scott Kitterman ] * Correct doc directory in README.Debian * Bump standards version to 3.9.4 without further change -- Scott Kitterman Wed, 17 Jul 2013 17:14:22 -0400 python3-defaults (3.3.2-1) unstable; urgency=low [ Scott Kitterman ] * Make python3.3 the default python3 * When X-Python3-Version is not present, do not describe it as missing, just indicate it is not there [ Matthias Klose ] * Bump version to 3.3.2. * Don't use the `u' abi flag when defaulting to 3.3. -- Scott Kitterman Sun, 14 Jul 2013 18:35:33 -0400 python3-defaults (3.3.0-3) experimental; urgency=low [ Piotr Ożarowski ] * pybuild: - add --ext-dest-dir (PYBUILD_EXT_DESTDIR) and --ext-pattern (PYBUILD_EXT_PATTERN) options to move files after install step - save before/after command logs if quiet mode is on - do not warn about limiting versions if there's only one - distutils plugin: do not skip build in install target (ugly workaround for yet another distutils "feature", closes: #701137) - do not run tests if DEB_BUILD_OPTIONS contains "nocheck" * dh_python3: - add version range to py3compile in maintainer scripts - no longer sensitive to trailing slash in private dir names (closes: #701215) * Bump minimum required dpkg-dev build dependency to 1.16.1~ (due to architecture.mk in debian/rules) [ Dmitry Shachnev ] * Include architecture.mk in debian/rules instead of defining DEB_HOST_* manually. * tests/t1: Build-depend on python3-all instead of python-all. * Make tests work without python-support installed. * debian/tests/control: Add a dependency on libjs-jquery (test1 contains a symlink to /usr/share/javascript/jquery/jquery.js). * Added missing docinfo to man pages, to fix a lintian warning (Closes: #702777). [ Matthias Klose ] * dh_python3: Use the multiarch tuple for the host (if DEB_HOST_MULTIARCH is set in the environment). * Add a libpython3-stdlib package (not yet built). -- Piotr Ożarowski Sun, 17 Mar 2013 13:47:29 +0100 python3-defaults (3.3.0-2) experimental; urgency=low [ Piotr Ożarowski ] * dh_python3: - add multiarch support (rename extensions in dist-packages) - rename foomodule.so to foo.so in dist-packages (for Python >= 3.3) * pybuild: - add --{before,after}-{clean,configure,build,install,test} command line options and many more PYBUILD_FOO environment vars (f.e. PYBUILD_DESTDIR, PYBUILD_DESTDIR_python3, PYBUILD_DESTDIR_python3.3-dbg) - add --disable command line option (to disable step, interpreter, version or any mix of them); drop --no-clean and --no-tests arguments (replaced by --disable clean, --disable test or --disable 'clean test') - add new build system to dh sequencer (dh --buildsystem=pybuild) - add manpage * Move python-docutils to Build-Depends (python3 package is now arch:any) [ Matthias Klose ] * Build dependency packages as architecture dependent packages. * Make python3, python3-{minimal,dev,dbg} Multi-Arch: allowed. * Don't use the `u' abi flag when defaulting to 3.3. * Build Multi-Arch: same packages libpython3-{dev,dbg} packages providing $(DEB_HOST_MULTIARCH)-python3-config symlinks. * Add Multi-Arch: same packages libpython3-all-{dev,dbg} (not yet built, python3.2 doesn't have support for multiarch). [ Dmitry Shachnev ] * debpython/interpreter.py: fix failing doctest (architecture no longer hardcoded) * Added DEP-8 tests (Closes: #698002). -- Piotr Ożarowski Sat, 12 Jan 2013 17:13:14 +0100 python3-defaults (3.3.0-1) experimental; urgency=low [ Piotr Ożarowski ] * Add Python 3.3 to the list of supported Python 3 versions and make it a default one. * dh_python3: - remove egg-info file/dir while moving files to common directory if the later one already contains it * rewrite dh_python3.1, py3compile.1 and py3clean.1 manpages in ReStructured Text * Add pybuild [ Scott Kitterman ] * Update Makefile to install pybuild * Fix file name typo in README.derivatives -- Scott Kitterman Mon, 26 Nov 2012 09:20:46 -0500 python3-defaults (3.2.3-7) unstable; urgency=low * Add Python 3.3 as a supported Python version. -- Matthias Klose Mon, 06 May 2013 03:05:02 +0200 python3-defaults (3.2.3-6) unstable; urgency=low [ Piotr Ożarowski ] * dh_python3 - ignore empty files while trying to normalize shebangs - mention the right file (debian/py3dist-overrides) while warning about guessed dependency - thanks to Sebastian Ramacher for the patch (Closes: #685067) - fix generating dependencies when maximum version is specified (Closes: #687060) * py3versions.py: fix parsing DEBPYTHON3_SUPPORTED env. variable (versions should be separated using comma, as in debian_defaults config file) * py3versions, debpython: close previously opened files - thanks to Dmitry Shachnev for the patch (Closes: #686587) [ Dmitry Shachnev ] [ Barry Warsaw ] * py3clean: Don't remove everything in the __pycache__ directory for system site package directories. Prevents bogus cleaning of unrelated *.pyc files. Original patch by Dmitry, with review, clean up, small modifications, and additional comments by Barry. (Closes: #685167) [ Barry Warsaw ] * dh_python3: Rework calculation of extension tags to add support for Python 3.3's different suffixes, and to allow for unadorned .so files to assume they are built with the default Python 3 version. Closes: 672178 * README.derivatives: It is no longer necessary to edit debian/py3versions.py since the values are taken from debian_defaults. Also added some text on how to separate the specification when multiple versions are supported. * Makefile: Fix the nosetests3 command. Closes: 690259 -- Piotr Ożarowski Sun, 21 Oct 2012 21:29:45 +0200 python3-defaults (3.2.3-5) unstable; urgency=low * dh_python3: - do not rewrite /usr/bin/python{,2.*} shebangs (Closes: #683294, /me still thinks it was a feature, not a bug) - parsing debian/control fields is now case insensitive * Change source format from native to 3.0 (native) -- Piotr Ożarowski Thu, 02 Aug 2012 23:26:08 +0200 python3-defaults (3.2.3-4) unstable; urgency=high * py3clean: really close #681389 -- Piotr Ożarowski Thu, 12 Jul 2012 22:45:47 -0600 python3-defaults (3.2.3-3) unstable; urgency=high * Yet another update in SHEBANG_RE to handle even more cases * test4 fixed to catch missing /usr/bin/python → /usr/bin/python3 rewrites * py3clean: accept --package *and* directory name at the same time (change missed in -1 upload, closes: #681389) * Bump minimum required python3 version to 3.2.3-3~ in packages with .py files (due to --package option that is added to py3compile/py3clean in rtupdate scripts) -- Piotr Ożarowski Thu, 12 Jul 2012 12:40:42 -0600 python3-defaults (3.2.3-2) unstable; urgency=high * Urgency high for grave bug because this will cause other packages to misbuild * Correct SHEBANG_RE in debpython/tools.py to not capture the 3 from python3 (Closes: #681235) -- Scott Kitterman Wed, 11 Jul 2012 11:51:46 -0400 python3-defaults (3.2.3-1) unstable; urgency=low * Bump upstream version to match current unstable/wheezy python3.2 version * dh_python3: - generates rtupdate scripts for private directories that compile files from given package only, add --compile-all to dh_python3's call if you want the old behaviour (i.e. compile also files (plugins?) provided by other packages, which do not use a helper/bytecompile them) - rewrite shebangs by default (disable via --no-shebang-rewrite), examples: + "/usr/bin/env python3*" → "/usr/bin/python3*" + "/usr/local/bin/python3 foo" → "/usr/bin/python3 foo" - new --shebang option to replace all shebangs in bin dirs (example: --shebang /usr/bin/python3) - translate Python version numbers into Debian ones for those require.txt items that have a pydist file with (uscan like) rules or PEP386 flag * py3versions, dh_python3, py3compile: allow to override system's list of supported Python3 versions via DEBPYTHON3_SUPPORTED and default Python3 version via DEBPYTHON3_DEFAULT env. variables * Debhelper's python3 sequence now inserts dh_python3 before dh_installinit -- Piotr Ożarowski Sat, 30 Jun 2012 15:20:39 +0200 python3-defaults (3.2.3~rc2-1) unstable; urgency=low [ Scott Kitterman ] * Drop unused XS-Python-Version support from dh_python3 * Remove unused debian/pyversions support from dh_python3 * Remove unused support for comma delimited lists of versions with X-Python3-Version from py3versions and debpython/debhelper.py (dh_python3) * Clean up log messages in py3versions a bit * Remove unused code related to parsing debian/pyversions from debian/py3versions * idle3 should Break as well as Replace python3 * Correct Python package names with hyphens in them being ignored (Closes: #657667) * Fix python3.2 related deprecation and resource warnings in debian/py3versions.py (Closes: #670471) * Drop -n from /usr/bin/idle3 invocations in debian/idle.desktop and debian/idle.menu (Closes: #671704) * dh_python3, py3versions: make comparison of X-Python-Version field names case-insensitive (Closes: #676225) - Change based on Piotr Ożarowski's change for python-defaults * Bump upstream version number to match python3.2 (3.2.3~rc2) * Bump minimum debhelper version to 7.0.50~ to support minumum version needed by tests * Add debian/python3-minimal.postinst.in and python3-minimal.prerm to support byte compiling py3versions.py (Closes: #672226) - byte compiling only works if py3compile is present, which it may not be on fresh installs, but removing .pyc files is reliable (best we can do without moving py3compile to python3-minimal * Move /usr/bin/py3versions -> ../share/python3/py3versions.py symlink from python3 to python3-minimal to match the change in python-defaults - Add Breaks/Replaces [ Piotr Ożarowski ] * Generate correct python3 (<< 3.X) dependencies when maximum Python 3 version is specified (Closes: #675703) -- Scott Kitterman Tue, 05 Jun 2012 23:58:13 -0400 python3-defaults (3.2.3~rc1-2) unstable; urgency=low * Fix max version expansion for -V/X-P-V to be the max version and not +1 * Move idle3.xpm symlink from python3 to idle3 and add Replaces * Add 'dependency package' to long description of python3-all, python3-all-dev, and python3-all-dbg -- Scott Kitterman Fri, 16 Mar 2012 17:19:58 -0400 python3-defaults (3.2.3~rc1-1) unstable; urgency=low * debpython/depends.py: - Add functional support for -V, specify list of supported Python versions for dh_python3 * Adjust upstream version number to match current python3.2 version * Bump standards version to 3.9.3 without further change -- Scott Kitterman Thu, 15 Mar 2012 00:43:38 -0400 python3-defaults (3.2.2-1) unstable; urgency=low [ Scott Kitterman ] * Update upstream version to match python3.2 * Add versioned idle3 package to idle3 depends (Closes: #637973) * Fix typo in debian/py3versions.1 (Closes: #651342) - Patch thanks to Daniel Stender * Specify Python 3 and not just Python in python3-doc/dbg descriptions * Add build-arch and build-indep targets in debian/rules * Add native-package-with-dash-version to source lintian overrides * Add idle3.lintian-overrides for menu-icon-missing since it is provided in the python3 package * Bump standards version to 3.9.2 without further change [ Matthias Klose ] * Add symlinks for python3-config man page. * Add symlinks for binaries and man pages including the abi flags. [ Piotr Ożarowski ] * py3compile: - fix -O option - speed up a bit (remove unnecessary interpreter calls) -- Scott Kitterman Wed, 11 Jan 2012 17:26:18 -0500 python3-defaults (3.2.2~rc1-2) unstable; urgency=medium * Medium urgency to avoid blocking the python2.7 transition * python3 now provides python3-profiler * Drop suggests on old (non-free) python3-profiler package -- Scott Kitterman Wed, 28 Sep 2011 11:29:05 -0400 python3-defaults (3.2.2~rc1-1) unstable; urgency=low * Update upstream version to match python3.2 * dh_python3: Assume .so files without tag in /usr/lib/python3/ are built for Python 3.2 instead of for Python 3.1 * dh_python3 and dh_python3.1: add --no-dbg-cleaning option (to disable removing files from debug packages) from dh_python2 -- Scott Kitterman Sun, 25 Sep 2011 01:14:16 -0400 python3-defaults (3.2-3) unstable; urgency=low * Fix a typo in dh_python3 and generate correct prerm scripts (with py3clean rather than pyclean, thanks to IRIE Shinsuke for bug reporta and a patch, closes: 622708, LP: #760401) -- Piotr Ożarowski Thu, 14 Apr 2011 21:44:29 +0200 python3-defaults (3.2-2) unstable; urgency=low [ Piotr Ożarowski ] * Drop Python 3.1 from supported Python 3 versions * python.mk: add py_builddir and py_builddir_sh macros. $(call py_builddir, 3.2) returns "build/lib.linux-x86_64-3.2" on amd64 [ Scott Kitterman ] * Upload to unstable -- Scott Kitterman Sun, 03 Apr 2011 19:02:43 -0400 python3-defaults (3.2-1) experimental; urgency=low [ Piotr Ożarowski ] * dh_python3 and py3compile: read /usr/share/python3/debian_defaults to get default Python 3 version and a list of supported Python 3 versions * py3compile: - let py_compile.py warn about syntax errors again * dh_python3: - fix checking shebangs in private directories (executable bit wasn't checked correctly) - private modules without extensions will not cause FTBFS anymore (closes: 617358, thanks to IRIE Shinsuke for the patch) - generate "python3 (>= 3.X), python3 (<< 3.Y)" dependencies if package provides public extensions - make egg-info files/dirs searches case insensitive [ Scott Kitterman ] * More Python/Python 3 in package descriptions -- Scott Kitterman Wed, 23 Mar 2011 22:48:56 -0400 python3-defaults (3.2~rc1-2) experimental; urgency=low * dh_python3: add support for DH_OPTIONS env. variable * disable check_versions test and drop python3 package from Build-Depends -- Piotr Ożarowski Thu, 20 Jan 2011 23:29:04 +0100 python3-defaults (3.2~rc1-1) experimental; urgency=low * Bump Python minimum version to >= 3.2~rc1 * dh_python3: ignore binary files while checking shebangs * py3compile: fix magic number check -- Piotr Ożarowski Wed, 19 Jan 2011 19:16:30 +0100 python3-defaults (3.2~b2-2) experimental; urgency=low * dh_python3 - fix moving files from old debug locations - move as many files to /usr/lib/python3/dist-packages as possible (files that cannot be shared between Python 3.X versions are left in original location for now) - add tag name to Python >= 3.2 extensions if they're missing (due to custom build system) in /usr/lib/pythonX.Y/dist-packages directories -- Piotr Ożarowski Thu, 06 Jan 2011 21:22:51 +0100 python3-defaults (3.2~b2-1) experimental; urgency=low [ Matthias Klose ] * Default to Python 3.2. * py3compile: - Don't over-optimize, check the timestamps of byte-code files. - Add options -f/--force, -O. - Copy stdout/stderr of py_compile processes in case of error. - Propagate the exit value of the py_compile processes. - Update manual page. * Bump depends to require the fixed pycompile for dh_python3 based package builds. * Don't touch the standard python library in rtupdate scripts. [ Piotr Ożarowski ] * dh_python3: - do not rename .so files outside dist-packages directory (Python 3.1 tag name will be added only in public directories) - generate proper dependencies/maintainer scripts for private directories with private extensions for more than one Python version - fix a crash in packages with private extension, test2 added (to test architecture dependent packages) * Invoke /usr/share/python3/runtime.d/ hooks in python3's preinst and postinst [ Scott Kitterman ] * Convert python.desktop to python3.desktop -- Scott Kitterman Thu, 23 Dec 2010 17:55:40 -0500 python3-defaults (3.1.3-15) experimental; urgency=low [ Matthias Klose ] * Depend on the 3.1.1 versions of the packages. [ Piotr Ożarowski ] * py3compile: do not try to check if interpreter is present when version range is empty -- Matthias Klose Tue, 30 Nov 2010 18:43:11 +0100 python3-defaults (3.1.2-15) experimental; urgency=low * debpython/version.py: Add 3.2 as supported version. -- Matthias Klose Sat, 16 Oct 2010 15:03:53 +0200 python3-defaults (3.1.2-14) experimental; urgency=low * Add python3.2 as a supported version. -- Matthias Klose Thu, 14 Oct 2010 16:42:31 +0200 python3-defaults (3.1.2-12) unstable; urgency=low * Upload to unstable -- Piotr Ożarowski Wed, 22 Sep 2010 23:20:10 +0200 python3-defaults (3.1.2-11) experimental; urgency=low * dh_python3: - egg renaming fixed - generate correct dependency for /usr/bin/python3 shebangs -- Piotr Ożarowski Wed, 15 Sep 2010 23:18:56 +0200 python3-defaults (3.1.2-10) experimental; urgency=low * dh_python3: fix python3:Versions and python3:Provides (now lists Python versions for which public extensions are provided by binary package) -- Piotr Ożarowski Mon, 13 Sep 2010 23:03:02 +0200 python3-defaults (3.1.2-9) experimental; urgency=low * dh_python3: add tag name to extension files that are missing it (to avoid conflicts with python3.2 in Wheezy) -- Piotr Ożarowski Sun, 12 Sep 2010 19:05:46 +0200 python3-defaults (3.1.2-8) experimental; urgency=low * py3compile: recognize /usr/lib/python3/ directories correctly (dh_python3: minimum required python version bumped to 3.1.2-8) -- Piotr Ożarowski Sun, 12 Sep 2010 17:26:21 +0200 python3-defaults (3.1.2-7) experimental; urgency=low [ Piotr Ożarowski ] * py3versions.py: open debian/control files with encoding='utf-8' as otherwise all my packages (with "ż" in debian/control) will FTBFS if user's locale is not set to UTF-8 (f.e. in build daemons) * dh_python3: - adjust to python3.1 3.1.2+20100909-1 changes - move files from /usr/lib/python3.X/dist-packages to /usr/lib/python3/dist-packages - set the right minimum required python3 package version in packages with private modules (for py3compile) - add dist_fallback file with a list of Python distribution name and Debian package name pairs (to be used as a fall back source for PyDist feature) - if dist_fallback and `dpkg -S` fails to find the right package name, fall back to package name recommended by Debian Python Policy (use debian/py3dist-overrides file to override) * py3compile, py3clean: adjust to PEP 3147 changes, -R option removed * Add manpages for dh_python3, py3compile and py3clean * Add README.derivatives (source package) [ Matthias Klose ] * python3: Install /usr/share/python3/python.mk. * python.mk (py_libdir): Return /usr/lib/python3/dist-packages for 3.x versions. * python.mk (py_pkgname): New macro to refer the package name depending on the python version. * Generate dependencies on python3 (>= 3.1.2-7~). * Require python3.1 3.1.2+20100909 as minimal version. -- Piotr Ożarowski Sun, 12 Sep 2010 15:54:25 +0200 python3-defaults (3.1.2-6) unstable; urgency=low [ Matthias Klose ] * Substitution variables for control files always start with a `python3' prefix (python:Versions -> python3:Versions, python:Provides -> python3:Provides). * Generate dependencies on python3 (>= 3.1.2-6~). [ Piotr Ożarowski ] * py3compile: do not hang if interpreters are not started in the same order as they're used * dh_python3: pass shallow=False to cmpfiles to make sure file comparison works as expected [ Scott Kitterman ] * Us X-Python3-Version for Python 3 instead of XS-Python-Version (which should just be used for Python) -- Piotr Ożarowski Fri, 13 Aug 2010 23:27:45 +0200 python3-defaults (3.1.2-5) unstable; urgency=medium * Add README.PyDist to python3-doc package * py3compile: compile public module for the right Python version * dh_python3: rename --depend to --depends, --recommend to --recommends and --suggest to --suggests * Bump Standards-Version to 3.9.1 -- Piotr Ożarowski Wed, 28 Jul 2010 22:34:17 +0200 python3-defaults (3.1.2-4) unstable; urgency=low * dh_python3: - add --depend, --recommend and --suggest command line options (use it if requires.txt doesn't contain dependency that package needs) - add {/usr,}/sbin to the list of directories with checked shebangs * py3compile: do not exit before all background byte compilation is finished -- Piotr Ożarowski Sun, 25 Jul 2010 16:25:04 +0200 python3-defaults (3.1.2-3) unstable; urgency=low [ Piotr Ożarowski ] * pyclean, pycompile: use .communicate() instead of .wait() to avoid hanging `dpkg -L PACKAGE` in few situations * dh_python3: follow Distribute and replace all non-alphanumeric characters with underscore in distribution name * Add python3.{postinst,prerm} scripts * python3-doc now suggests python3-examples * Bump Standards-Version to 3.9.0 [ Scott Kitterman ] * Drop deprecated call to dh_desktop from debian/rules * Bump PREVVER to 3.1.2-3~ for support for stdin in py_compile.py [ Matthias Klose ] * Provide the python3.pc symlink in python3-dev. * Call py3clean/py3compile on rtupdate in generated scripts. -- Matthias Klose Tue, 20 Jul 2010 20:20:01 +0200 python3-defaults (3.1.2-2) unstable; urgency=low * Add Vcs-Browser field * Add some lintian overrides (for false positives) - bump minimum required debhelper version to 6.0.7 (due to dh_lintian) * py3compile, py3clean and dh_python3 moved to python3 package * dh_python3: - some bugs fixed (encoding problems, parsing Python-Version, few python vs python3 leftovers) -- Piotr Ożarowski Wed, 23 Jun 2010 22:57:23 +0200 python3-defaults (3.1.2-1) unstable; urgency=low [ Matthias Klose ] * Depend on the 3.1.2 versions of the packages. * Add py3clean, py3compile binaries to be called from python3-* maintainer scripts. * Don't allow installation of a mix of defaults packages for different python3 versions. [ Scott Kitterman ] * Provide default and supported Python3 versions (3.1 to start) - Rename pyversions(.py)(.1) to py3versions(.py)(.1) - Port py3versions.py to Python 3 - Update py3versions to use python3 specific locations - Update py3versions to ignore all, current and python versions < 3.0 and not to use debian/pyversions - Update debian_defaults for python3 - Install debian_defaults for python3 - Update debian/rules * Update debian/copyright from python3.1 LICENSE file * Add myself to uploaders [ Piotr Ożarowski ] * Add dh_python3, py3compile and py3clean * Add myself to Uploaders -- Matthias Klose Fri, 18 Jun 2010 00:10:21 +0200 python3-defaults (3.1.1-1) unstable; urgency=low * Depend on the 3.1.1 versions of the packages. -- Matthias Klose Fri, 22 Jan 2010 17:44:37 +0100 python3-defaults (3.1-1) experimental; urgency=low * Depend on the 3.1 versions of the packages. -- Matthias Klose Thu, 23 Jul 2009 17:27:33 +0200 python3-defaults (3.0.1-0ubuntu4) jaunty; urgency=low * Make idle3 actually run with /usr/bin/python3. (LP: #336381) * Remove unused idle.sh that led to the previous confusion. -- Anders Kaseorg Thu, 12 Mar 2009 15:37:50 -0400 python3-defaults (3.0.1-0ubuntu3) jaunty; urgency=low * Make idle3 run with /usr/bin/python3, not /usr/bin/python. (LP: #336381) * Remove Essential: yes from python3-minimal, and reduce the Priority of python3 and python3-minimal to optional. (LP: #330613) -- Anders Kaseorg Sun, 08 Mar 2009 18:30:38 -0400 python3-defaults (3.0.1-0ubuntu2) jaunty; urgency=low * Depend on the 3.0.1 versions of the packages. -- Matthias Klose Mon, 16 Feb 2009 23:23:06 +0100 python3-defaults (3.0~b3-0ubuntu1) intrepid; urgency=low * Build new defaults for python3. -- Matthias Klose Mon, 15 Sep 2008 22:21:59 +0000 python-defaults (2.5.2-1ubuntu1) intrepid; urgency=low * Merge with Debian; remaining changes: - Build the -doc package from this source package. - Omit Debian specific upgrade code. - Regenerate the control file. -- Matthias Klose Mon, 23 Jun 2008 13:13:51 +0200 python-defaults (2.5.2-0ubuntu1) hardy; urgency=low * Depend on the 2.5.2 versions of the packages. -- Matthias Klose Mon, 10 Mar 2008 18:03:30 +0000 python-defaults (2.5.1-1ubuntu2) gutsy; urgency=low * Temporarily loosen the dependency on python2.5 to allow python2.5 to build on powerpc and sparc. -- Matthias Klose Fri, 27 Apr 2007 00:00:32 +0200 python-defaults (2.5.1-1ubuntu1) gutsy; urgency=low * Depend on the 2.5.1 versions of the packages. -- Matthias Klose Thu, 26 Apr 2007 11:23:17 +0200 python-defaults (2.5.1~rc1-0ubuntu3) feisty; urgency=low * Fix versioned build dependency on python2.5. -- Matthias Klose Fri, 13 Apr 2007 06:37:58 +0200 python-defaults (2.5.1~rc1-0ubuntu2) feisty; urgency=low * Add a sanity check, that /usr/bin/python points to the default python version. Users tend to modify this symlink, which then breaks stuff in obscure ways. Ubuntu #75557, Debian #418002. -- Matthias Klose Fri, 6 Apr 2007 17:47:24 +0200 python-defaults (2.5.1~rc1-0ubuntu1) feisty; urgency=low * Depend on the 2.5.1~rc1 versions of the packages. -- Matthias Klose Fri, 6 Apr 2007 11:13:10 +0000 python-defaults (2.5-0ubuntu6) feisty; urgency=low * python-dbg: Add a python-dbg-config binary. -- Matthias Klose Sat, 17 Feb 2007 21:39:44 +0100 python-defaults (2.5-0ubuntu5) feisty; urgency=low * python-all-dbg: Tighten dependencies on the python2.x-dbg packages. * python-dbg: Provide python-gdbm-dbg, python-tk-dbg, link to README.debug, SpecialBuilds.txt.gz. * python-dev: Add an unversioned python-config binary. * Readd build-dependency on python-docutils. * Set Ubuntu maintainer address. * Update the FAQ. -- Matthias Klose Fri, 16 Feb 2007 18:18:06 +0100 python-defaults (2.5-0ubuntu4) feisty; urgency=low * New package python-all-dbg. -- Matthias Klose Fri, 9 Feb 2007 01:16:09 +0100 python-defaults (2.5-0ubuntu3) feisty; urgency=low * Temporarily remove build-dependency on python-docutils. -- Matthias Klose Fri, 12 Jan 2007 13:06:50 +0000 python-defaults (2.5-0ubuntu2) feisty; urgency=low * Fix icon for desktop file. * Robustify building the faq html pages. * Make the suggestions of various packages versioned. * Recommend depending on "pythonX.X-foo, python-foo" instead of recommending to only depend on "pythonX.X-foo" when a particular version is needed to permit upgrades from real packages to virtual ones. (Loic Minier). -- Matthias Klose Fri, 12 Jan 2007 11:42:02 +0000 python-defaults (2.5-0ubuntu1) feisty; urgency=low * Make python2.5 the default version. -- Matthias Klose Fri, 12 Jan 2007 09:10:52 +0000 python-defaults (2.4.4-1ubuntu2) feisty; urgency=low * python-minimal is essential, not python. -- Matthias Klose Thu, 7 Dec 2006 14:25:20 +0000 python-defaults (2.4.4-1ubuntu1) feisty; urgency=low * Merge with Debian unstable. - Backout: Add 2.5 to unsupported-versions. * Build the FAQ again. -- Matthias Klose Thu, 16 Nov 2006 15:21:31 -0800 python-defaults (2.4.4-1) unstable; urgency=medium * Depend on the 2.4.4 versions of the packages. * Sync pyversions.py with python-central. * Move 2.3 to old-versions, from supported-versions. * Add 2.5 to unsupported-versions. -- Matthias Klose Sun, 29 Oct 2006 11:06:39 +0100 python-defaults (2.4.3-11ubuntu3) edgy; urgency=low * Temporarily remove the FAQ and the build-dependency on python-docutils, so that the build dependencies can be installed. -- Matthias Klose Wed, 20 Sep 2006 17:28:47 +0000 python-defaults (2.4.3-11ubuntu2) edgy; urgency=low * debian/pyversions: - merged the changes from python-central to support older python version (and not break on upgrades) -- Michael Vogt Wed, 20 Sep 2006 16:42:12 +0200 python-defaults (2.4.3-11ubuntu1) edgy; urgency=low * Merge with Debian unstable. -- Matthias Klose Fri, 8 Sep 2006 00:22:21 +0200 python-defaults (2.4.3-11) unstable; urgency=low * Add a conflict to python-central (<< 0.5.5). -- Matthias Klose Sun, 13 Aug 2006 19:32:59 +0000 python-defaults (2.4.3-10) unstable; urgency=low * Upload to unstable. Closes: #347440, #360851. * Let the preinst fail on the first failing pre-rtupdate hook, after running the corresponding failed-pre-rtupdate hook. * Reflect renaming of the docutils binaries. Closes: #377601. * Update the upstream FAQ. -- Matthias Klose Sat, 12 Aug 2006 20:28:30 +0200 python-defaults (2.4.3-9) experimental; urgency=low * Fix syntax error in python.preinst. Closes: #381673. -- Matthias Klose Sun, 6 Aug 2006 12:39:34 +0000 python-defaults (2.4.3-8) experimental; urgency=low * idle: Depend on python-tk, add desktop and menu files. -- Matthias Klose Sat, 5 Aug 2006 18:38:31 +0000 python-defaults (2.4.3-7) experimental; urgency=low * Update pyversions.py from 2.3.5-11. * Fix pyversions(1), -r takes exactly one parameter. * idle: Remove the dependency on idle-pythonX.Y, add start script and man page. -- Matthias Klose Sat, 5 Aug 2006 17:34:43 +0000 python-defaults (2.4.3-6) experimental; urgency=low * Remove python's dependency on python-central. Closes: #372658. * On upgrade of the runtime to a new major version, call the hooks (executable files) in /usr/share/python/runtime.d/*.rtupdate. - in python.preinst, call the script with parameters pre-rtupdate . run all hooks, then return exit with the correct exit status. - in python.postinst, call the script with parameters rtupdate . run all hooks, then return exit with the correct exit status. - in python.postinst, call the script with parameters post-rtupdate . run all hooks, then return exit with the correct exit status. * pyversions -r: If the XS-Python-Version field cannot be found in debian/control, fall back to debian/pyversions for the version information. Return with an error code, if the intersection of the versions in debian/pyversions and the supported python versions is empty. Fall back to the supported versions if no version information can be found. Based on a patch from Raphael Hertzog. * Reflect renaming of the docutils binaries. Closes: #377601. -- Matthias Klose Sat, 5 Aug 2006 17:54:43 +0200 python-defaults (2.4.3-5ubuntu1) edgy; urgency=low * Synchronize with Debian experimental. * Remove python's dependency on python-central. On upgrade of the runtime, call hooks /usr/share/python/runtime.d/*.rtupdate. Addresses: #372658. * pyversions -r: If the XS-Python-Version field cannot be found in debian/control, fall back to debian/pyversions for the version information. Return with an error code, if the intersection of the versions in debian/pyversions and the supported python versions is empty. Fall back to the supported versions if no version information can be found. Based on a patch from Raphael Hertzog. -- Matthias Klose Wed, 5 Jul 2006 05:11:42 +0000 python-defaults (2.4.3-5) experimental; urgency=low * Tighten dependencies between packages built from this source. A versioned dependency on python-all / python-all-dev is enough to depend on the same version of python / python-dev. * python: Conflict with python-central (<< 0.4.17). * python: Depend on a python2.4 built for the updated Python policy. * python: Conflict with a python2.3 using the old Python policy. -- Matthias Klose Fri, 16 Jun 2006 18:15:00 +0200 python-defaults (2.4.3-4) experimental; urgency=low * Include version 0.4.1.0 of the python policy. * Fix 'pyversions -i'. -- Matthias Klose Tue, 13 Jun 2006 09:44:22 +0200 python-defaults (2.4.3-3) experimental; urgency=low * Point to the draft of the reworked Python policy. * Fix 'pyversions -r current' (Raphael Hertzog). -- Matthias Klose Mon, 12 Jun 2006 13:40:52 +0200 python-defaults (2.4.3-02) experimental; urgency=low * Really do not build python-doc. -- Matthias Klose Sun, 11 Jun 2006 23:25:02 +0000 python-defaults (2.4.3-1ubuntu1) edgy; urgency=low * Let the -all packages depend on the default packages (closes: #365219). * Add /usr/share/python/debian_defaults for some default values (i.e. the supported python versions). * Add /etc/python/debian_config for byte-compilation options. * Add a pyversions script to give information about python versions and parse the XS-Python-Version attribute. * Include version 0.4.1.0 of the python policy. -- Matthias Klose Tue, 13 Jun 2006 13:22:43 +0200 python-defaults (2.4.3-01) experimental; urgency=low * Do not build the python-doc package from this source. -- Matthias Klose Sun, 11 Jun 2006 23:59:17 +0200 python-defaults (2.4.3-0) experimental; urgency=low * Upload to experimental. * Do not build the python-tk and python-gdbm packages from this source. * Let the -all packages depend on the default packages (closes: #365219). * Add /usr/share/python/debian_defaults for some default values (i.e. the supported python versions). * Add /etc/python/debian_config for byte-compilation options. * Add a pyversions script to give information about python versions and parse the XS-Python-Version attribute. -- Matthias Klose Sun, 11 Jun 2006 12:57:03 +0000 python-defaults (2.4.2-1) unstable; urgency=low * Change the default python version to 2.4. * Depend on python-central. -- Matthias Klose Thu, 12 Jan 2006 01:16:10 +0000 python-defaults (2.3.5-4) unstable; urgency=low * Add a package python-minimal. This package still depends on python2.3, will depend on python2.4-minimal when changing the default python version. * Add two dependency packages python-all and python-all-dev. These packages are used as build dependencies to determine the set of python version and implementations, which should be / currently are supported. Currently it depends on python2.3 and python2.4. Future versions may add an updated version of jython and ironpython. * Update FAQ. -- Matthias Klose Thu, 12 Jan 2006 00:32:32 +0100 python-defaults (2.3.5-3) unstable; urgency=low * Add python-dbg package. * debian/control.in: idle enhances python. -- Matthias Klose Sun, 19 Jun 2005 13:49:16 +0200 python-defaults (2.3.5-2) unstable; urgency=low * Add valgrind support file /usr/lib/valgrind/python.supp (closes: #291128). * python-doc: Add an conflict/replace to older python packages. Closes: #297266. -- Matthias Klose Sat, 19 Mar 2005 22:49:29 +0100 python-defaults (2.3.5-1) unstable; urgency=low * Depend on python-2.3.5 packages. * Update FAQ. * python suggests python-profiler. -- Matthias Klose Sat, 12 Feb 2005 19:26:48 +0100 python-defaults (2.3.4-6) unstable; urgency=low * Add an 'Enhances: konsole' to the python package (closes: #286161). -- Matthias Klose Sun, 16 Jan 2005 12:53:58 +0100 python-defaults (2.3.4-5) unstable; urgency=low * Add conflict/replaces to ooold python-base package (closes: #279035). -- Matthias Klose Sun, 14 Nov 2004 11:44:14 +0100 python-defaults (2.3.4-4) unstable; urgency=low * Regenerate control file after adding python-docutils build dependency. Closes: #270177. -- Matthias Klose Mon, 6 Sep 2004 07:19:49 +0200 python-defaults (2.3.4-3) testing-proposed-updates; urgency=low * Unmodified 2.3.4-3sid, destination sarge, fixing build failure. -- Matthias Klose Fri, 20 Aug 2004 18:24:25 +0200 python-defaults (2.3.4-3sid) unstable; urgency=low * Add build dependency on python-docutils (closes: #266550). -- Matthias Klose Wed, 18 Aug 2004 12:30:37 +0200 python-defaults (2.3.4-2sid) unstable; urgency=low * Add pdb and pdb.1 symlinks. * Update FAQ. -- Matthias Klose Tue, 17 Aug 2004 16:17:06 +0200 python-defaults (2.3.4-1) unstable; urgency=low * Depend on python-2.3.4 packages. * Update FAQ. -- Matthias Klose Mon, 10 May 2004 06:58:24 +0200 python-defaults (2.3.3-7) unstable; urgency=low * Fix symlinks to proposed policy files (closes: #234874). -- Matthias Klose Thu, 26 Feb 2004 22:28:07 +0100 python-defaults (2.3.3-6) unstable; urgency=low * Build the default packages from a separate source package to ease migration between python versions. * Update to the proposed python-policy: byte-compile using -E. -- Matthias Klose Wed, 4 Feb 2004 23:16:35 +0100 python3-defaults-3.6.7/debian/chunk.xsl0000664000000000000000000000140113305601050014677 0ustar 1 0 1 1 1 _blank 1 python3-defaults-3.6.7/debian/compat0000664000000000000000000000000213305601050014241 0ustar 9 python3-defaults-3.6.7/debian/control0000664000000000000000000002432413364125761014472 0ustar Source: python3-defaults Section: python Priority: optional Maintainer: Ubuntu Developers XSBC-Original-Maintainer: Matthias Klose Uploaders: Piotr Ożarowski Build-Depends: debhelper (>= 9), dpkg-dev (>= 1.17.11), python3.6 (>= 3.6.7-1~), lsb-release, python3-minimal:any, python3-docutils, docbook-xml, docbook-xsl, w3m, xsltproc, Standards-Version: 4.2.1 Homepage: https://www.python.org/ Vcs-Git: https://salsa.debian.org/cpython-team/python3-defaults.git Vcs-Browser: https://salsa.debian.org/cpython-team/python3-defaults Package: python3 Architecture: any Multi-Arch: allowed Pre-Depends: python3-minimal (= ${binary:Version}) Depends: python3.6 (>= 3.6.7-1~), libpython3-stdlib (= ${binary:Version}), ${misc:Depends} Suggests: python3-doc (>= ${binary:Version}), python3-tk (>= 3.6.7-1~) , python3-venv (>= ${binary:Version}) Replaces: python3-minimal (<< 3.1.2-2) Provides: python3-profiler Description: interactive high-level object-oriented language (default python3 version) Python, the high-level, interactive object oriented language, includes an extensive class library with lots of goodies for network programming, system administration, sounds and graphics. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v3.6). XB-Cnf-Extra-Commands: python XB-Cnf-Priority-Bonus: 5 Package: python3-venv Architecture: any Multi-Arch: allowed Depends: python3.6-venv (>= 3.6.7-1~), python3 (= ${binary:Version}), python3-distutils (>= 3.6.7-1~), ${misc:Depends} Description: pyvenv-3 binary for python3 (default python3 version) Python, the high-level, interactive object oriented language, includes an extensive class library with lots of goodies for network programming, system administration, sounds and graphics. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v3.6). Package: python3-minimal Architecture: any Multi-Arch: allowed Pre-Depends: python3.6-minimal (>= 3.6.7-1~) Depends: dpkg (>= 1.13.20), ${misc:Depends} Description: minimal subset of the Python language (default python3 version) This package contains the interpreter and some essential modules. It's used in the boot process for some basic tasks. See /usr/share/doc/python3.6-minimal/README.Debian for a list of the modules contained in this package. Cnf-Visible-Pkgname: python3 Package: python3-examples Architecture: all Multi-Arch: foreign Depends: python3 (>= ${binary:Version}), python3.6-examples (>= 3.6.7-1~), ${misc:Depends} Description: examples for the Python language (default version) Examples, Demos and Tools for Python. These are files included in the upstream Python distribution. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v3.6). Package: python3-dev Architecture: any Multi-Arch: allowed Depends: python3 (= ${binary:Version}), libpython3-dev (= ${binary:Version}), python3.6-dev (>= 3.6.7-1~), python3-distutils (>= 3.6.7-1~), ${misc:Depends}, dh-python Replaces: python3.1 (<< 3.1.2+20100706-3) Description: header files and a static library for Python (default) Header files, a static library and development tools for building Python modules, extending the Python interpreter or embedding Python in applications. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v3.6). Package: libpython3-dev Architecture: any Multi-Arch: same Section: libdevel Depends: libpython3.6-dev (>= 3.6.7-1~), ${misc:Depends} Description: header files and a static library for Python (default) Header files, a static library and development tools for building Python modules, extending the Python interpreter or embedding Python in applications. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v3.6). Package: libpython3-stdlib Architecture: any Multi-Arch: same Depends: libpython3.6-stdlib (>= 3.6.7-1~), ${misc:Depends} Description: interactive high-level object-oriented language (default python3 version) Python, the high-level, interactive object oriented language, includes an extensive class library with lots of goodies for network programming, system administration, sounds and graphics. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v3.6). Package: idle Architecture: all Depends: python3 (>= ${binary:Version}), python3-tk, ${misc:Depends}, idle-python3.6 Enhances: python3 Breaks: idle3 (<< 3.6.2-2) Replaces: idle3 (<< 3.6.2-2) Description: IDE for Python using Tkinter (default version) IDLE is an Integrated Development Environment for Python. IDLE is written using Tkinter and therefore quite platform-independent. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v3.6). Package: idle3 Architecture: all Section: oldlibs Depends: python3 (>= ${binary:Version}), idle (>= ${binary:Version}), ${misc:Depends} Description: IDE for Python using Tkinter (transitional package) IDLE is an Integrated Development Environment for Python. . This package is a transitional package, you can safely remove it. Package: python3-doc Section: doc Architecture: all Multi-Arch: foreign Depends: python3.6-doc (>= 3.6.7-1~), ${misc:Depends} Suggests: python3 (>= ${binary:Version}), python3-examples Description: documentation for the high-level object-oriented language Python 3 This is the official set of documentation for the interactive high-level object-oriented language Python 3 (v3.6). All documents are provided in HTML format, some in info format. The package consists of nine documents: . * Tutorial * Python Library Reference * Macintosh Module Reference * Python Language Reference * Extending and Embedding Python * Python/C API Reference * Installing Python Modules * Documenting Python * Distributing Python Modules . This package is a dependency package, which depends on Debian's default Python 3 version (currently v3.6). Package: python3-dbg Architecture: any Multi-Arch: allowed Section: debug Depends: python3 (= ${binary:Version}), libpython3-dbg (= ${binary:Version}), python3.6-dbg (>= 3.6.7-1~), ${misc:Depends} Description: debug build of the Python 3 Interpreter (version 3.6) Python 3 interpreter configured with --pydebug. Dynamically loaded modules are searched in /usr/lib/python3.6/lib-dynload/debug first. Package: libpython3-dbg Architecture: any Multi-Arch: same Section: debug Depends: libpython3.6-dbg (>= 3.6.7-1~), ${misc:Depends} Description: debug build of the Python 3 Interpreter (version 3.6) Python 3 interpreter configured with --pydebug. Dynamically loaded modules are searched in /usr/lib/python3.6/lib-dynload/debug first. Package: python3-all Architecture: any Multi-Arch: allowed Depends: python3 (= ${binary:Version}), ${misc:Depends}, dh-python, python3-distutils (>= 3.6.7-1~), python3.6, Description: package depending on all supported Python 3 runtime versions The package currently depends on python3.6, in the future, dependencies on jython (Python for a JVM) and ironpython (Python for Mono) may be added. . This package is a dependency package used as a build dependency for other packages to avoid hardcoded dependencies on specific Python 3 runtimes. Package: python3-all-dev Architecture: any Multi-Arch: allowed Depends: python3 (= ${binary:Version}), libpython3-all-dev (= ${binary:Version}), python3-all (= ${binary:Version}), python3-dev (= ${binary:Version}), ${misc:Depends}, python3.6-dev, Description: package depending on all supported Python 3 development packages The package currently depends on python3.6-dev, in the future, dependencies on jython (Python for a JVM) and ironpython (Python for Mono) may be added. . This package is a dependency package used as a build dependency for other packages to avoid hardcoded dependencies on specific Python 3 development packages. Package: python3-all-dbg Architecture: any Multi-Arch: allowed Section: debug Depends: python3 (= ${binary:Version}), libpython3-all-dbg (= ${binary:Version}), python3-all (= ${binary:Version}), python3-dbg (= ${binary:Version}), ${misc:Depends}, python3.6-dbg, Description: package depending on all supported Python 3 debugging packages The package currently depends on python3.6-dbg, in the future, dependencies on jython (Python for a JVM) and ironpython (Python for Mono) may be added. . This package is a dependency package used as a build dependency for other packages to avoid hardcoded dependencies on specific Python 3 debug packages. Package: libpython3-all-dev Architecture: any Multi-Arch: same Section: libdevel Depends: libpython3-dev (= ${binary:Version}), ${misc:Depends}, libpython3.6-dev, Description: package depending on all supported Python 3 development packages The package currently depends on libpython3.6-dev, in the future, dependencies on jython (Python for a JVM) and ironpython (Python for Mono) may be added. . This package is a dependency package used as a build dependency for other packages to avoid hardcoded dependencies on specific Python 3 development packages. Package: libpython3-all-dbg Architecture: any Multi-Arch: same Section: debug Depends: libpython3-dbg (= ${binary:Version}), ${misc:Depends}, libpython3.6-dbg Description: package depending on all supported Python 3 debugging packages The package currently depends on libpython3.6-dbg, in the future, dependencies on jython (Python for a JVM) and ironpython (Python for Mono) may be added. . This package is a dependency package used as a build dependency for other packages to avoid hardcoded dependencies on specific Python 3 debug packages. Package: 2to3 Architecture: all Multi-Arch: foreign Depends: python3-lib2to3 (>= 3.6.7-1~), python3 (>= ${binary:Version}), ${misc:Depends} Breaks: python (<< 2.7.14-4) Replaces: python (<< 2.7.14-4) Description: 2to3 binary using python3 Python, the high-level, interactive object oriented language, includes an extensive class library with lots of goodies for network programming, system administration, sounds and graphics. . This package is a dependency package, which depends on Debian's default Python 3 2to3 version (currently v3.6). python3-defaults-3.6.7/debian/control.in0000664000000000000000000002440513364125434015074 0ustar Source: python3-defaults Section: python Priority: optional Maintainer: Ubuntu Developers XSBC-Original-Maintainer: Matthias Klose Uploaders: Piotr Ożarowski Build-Depends: debhelper (>= 9), @bd_i586@ lsb-release, python3-minimal:any, python3-docutils, docbook-xml, docbook-xsl, w3m, xsltproc, Standards-Version: 4.2.1 Homepage: https://www.python.org/ Vcs-Git: https://salsa.debian.org/cpython-team/python3-defaults.git Vcs-Browser: https://salsa.debian.org/cpython-team/python3-defaults Package: python3 Architecture: any Multi-Arch: allowed Pre-Depends: python3-minimal (= ${binary:Version}) Depends: python@VER@ (>= @UPSTRVER@), libpython3-stdlib (= ${binary:Version}), ${misc:Depends} Suggests: python3-doc (>= ${binary:Version}), python3-tk (>= @STDLIBVER@) , python3-venv (>= ${binary:Version}) Replaces: python3-minimal (<< 3.1.2-2) Provides: python3-profiler Description: interactive high-level object-oriented language (default python3 version) Python, the high-level, interactive object oriented language, includes an extensive class library with lots of goodies for network programming, system administration, sounds and graphics. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v@VER@). XB-Cnf-Extra-Commands: python XB-Cnf-Priority-Bonus: 5 Package: python3-venv Architecture: any Multi-Arch: allowed Depends: python@VER@-venv (>= @UPSTRVER@), python3 (= ${binary:Version}), python3-distutils (>= @STDLIBVER@), ${misc:Depends} Description: pyvenv-3 binary for python3 (default python3 version) Python, the high-level, interactive object oriented language, includes an extensive class library with lots of goodies for network programming, system administration, sounds and graphics. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v@VER@). Package: python3-minimal Architecture: any Multi-Arch: allowed Pre-Depends: python@VER@-minimal (>= @UPSTRVER@) Depends: dpkg (>= 1.13.20), ${misc:Depends} Description: minimal subset of the Python language (default python3 version) This package contains the interpreter and some essential modules. It's used in the boot process for some basic tasks. See /usr/share/doc/python@VER@-minimal/README.Debian for a list of the modules contained in this package. Cnf-Visible-Pkgname: python3 Package: python3-examples Architecture: all Multi-Arch: foreign Depends: python3 (>= ${binary:Version}), python@VER@-examples (>= @UPSTRVER@), ${misc:Depends} Description: examples for the Python language (default version) Examples, Demos and Tools for Python. These are files included in the upstream Python distribution. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v@VER@). Package: python3-dev Architecture: any Multi-Arch: allowed Depends: python3 (= ${binary:Version}), libpython3-dev (= ${binary:Version}), python@VER@-dev (>= @UPSTRVER@), python3-distutils (>= @STDLIBVER@), ${misc:Depends}, dh-python Replaces: python3.1 (<< 3.1.2+20100706-3) Description: header files and a static library for Python (default) Header files, a static library and development tools for building Python modules, extending the Python interpreter or embedding Python in applications. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v@VER@). Package: libpython3-dev Architecture: any Multi-Arch: same Section: libdevel Depends: libpython@VER@-dev (>= @UPSTRVER@), ${misc:Depends} Description: header files and a static library for Python (default) Header files, a static library and development tools for building Python modules, extending the Python interpreter or embedding Python in applications. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v@VER@). Package: libpython3-stdlib Architecture: any Multi-Arch: same Depends: libpython@VER@-stdlib (>= @UPSTRVER@), ${misc:Depends} Description: interactive high-level object-oriented language (default python3 version) Python, the high-level, interactive object oriented language, includes an extensive class library with lots of goodies for network programming, system administration, sounds and graphics. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v@VER@). Package: idle Architecture: all Depends: python3 (>= ${binary:Version}), python3-tk, ${misc:Depends}, idle-python@VER@ Enhances: python3 Breaks: idle3 (<< 3.6.2-2) Replaces: idle3 (<< 3.6.2-2) Description: IDE for Python using Tkinter (default version) IDLE is an Integrated Development Environment for Python. IDLE is written using Tkinter and therefore quite platform-independent. . This package is a dependency package, which depends on Debian's default Python 3 version (currently v@VER@). Package: idle3 Architecture: all Section: oldlibs Depends: python3 (>= ${binary:Version}), idle (>= ${binary:Version}), ${misc:Depends} Description: IDE for Python using Tkinter (transitional package) IDLE is an Integrated Development Environment for Python. . This package is a transitional package, you can safely remove it. Package: python3-doc Section: doc Architecture: all Multi-Arch: foreign Depends: python@VER@-doc (>= @UPSTRVER@), ${misc:Depends} Suggests: python3 (>= ${binary:Version}), python3-examples Description: documentation for the high-level object-oriented language Python 3 This is the official set of documentation for the interactive high-level object-oriented language Python 3 (v@VER@). All documents are provided in HTML format, some in info format. The package consists of nine documents: . * Tutorial * Python Library Reference * Macintosh Module Reference * Python Language Reference * Extending and Embedding Python * Python/C API Reference * Installing Python Modules * Documenting Python * Distributing Python Modules . This package is a dependency package, which depends on Debian's default Python 3 version (currently v@VER@). Package: python3-dbg Architecture: any Multi-Arch: allowed Section: debug Depends: python3 (= ${binary:Version}), libpython3-dbg (= ${binary:Version}), python@VER@-dbg (>= @UPSTRVER@), ${misc:Depends} Description: debug build of the Python 3 Interpreter (version @VER@) Python 3 interpreter configured with --pydebug. Dynamically loaded modules are searched in /usr/lib/python@VER@/lib-dynload/debug first. Package: libpython3-dbg Architecture: any Multi-Arch: same Section: debug Depends: libpython@VER@-dbg (>= @UPSTRVER@), ${misc:Depends} Description: debug build of the Python 3 Interpreter (version @VER@) Python 3 interpreter configured with --pydebug. Dynamically loaded modules are searched in /usr/lib/python@VER@/lib-dynload/debug first. Package: python3-all Architecture: any Multi-Arch: allowed Depends: python3 (= ${binary:Version}), ${misc:Depends}, dh-python, python3-distutils (>= @STDLIBVER@), python3.6, Description: package depending on all supported Python 3 runtime versions The package currently depends on python3.6, in the future, dependencies on jython (Python for a JVM) and ironpython (Python for Mono) may be added. . This package is a dependency package used as a build dependency for other packages to avoid hardcoded dependencies on specific Python 3 runtimes. Package: python3-all-dev Architecture: any Multi-Arch: allowed Depends: python3 (= ${binary:Version}), libpython3-all-dev (= ${binary:Version}), python3-all (= ${binary:Version}), python3-dev (= ${binary:Version}), ${misc:Depends}, python3.6-dev, Description: package depending on all supported Python 3 development packages The package currently depends on python3.6-dev, in the future, dependencies on jython (Python for a JVM) and ironpython (Python for Mono) may be added. . This package is a dependency package used as a build dependency for other packages to avoid hardcoded dependencies on specific Python 3 development packages. Package: python3-all-dbg Architecture: any Multi-Arch: allowed Section: debug Depends: python3 (= ${binary:Version}), libpython3-all-dbg (= ${binary:Version}), python3-all (= ${binary:Version}), python3-dbg (= ${binary:Version}), ${misc:Depends}, python3.6-dbg, Description: package depending on all supported Python 3 debugging packages The package currently depends on python3.6-dbg, in the future, dependencies on jython (Python for a JVM) and ironpython (Python for Mono) may be added. . This package is a dependency package used as a build dependency for other packages to avoid hardcoded dependencies on specific Python 3 debug packages. Package: libpython3-all-dev Architecture: any Multi-Arch: same Section: libdevel Depends: libpython3-dev (= ${binary:Version}), ${misc:Depends}, libpython3.6-dev, Description: package depending on all supported Python 3 development packages The package currently depends on libpython3.6-dev, in the future, dependencies on jython (Python for a JVM) and ironpython (Python for Mono) may be added. . This package is a dependency package used as a build dependency for other packages to avoid hardcoded dependencies on specific Python 3 development packages. Package: libpython3-all-dbg Architecture: any Multi-Arch: same Section: debug Depends: libpython3-dbg (= ${binary:Version}), ${misc:Depends}, libpython3.6-dbg Description: package depending on all supported Python 3 debugging packages The package currently depends on libpython3.6-dbg, in the future, dependencies on jython (Python for a JVM) and ironpython (Python for Mono) may be added. . This package is a dependency package used as a build dependency for other packages to avoid hardcoded dependencies on specific Python 3 debug packages. Package: 2to3 Architecture: all Multi-Arch: foreign Depends: python3-lib2to3 (>= @STDLIBVER@), python3 (>= ${binary:Version}), ${misc:Depends} Breaks: python (<< 2.7.14-4) Replaces: python (<< 2.7.14-4) Description: 2to3 binary using python3 Python, the high-level, interactive object oriented language, includes an extensive class library with lots of goodies for network programming, system administration, sounds and graphics. . This package is a dependency package, which depends on Debian's default Python 3 2to3 version (currently v@VER@). python3-defaults-3.6.7/debian/copyright0000664000000000000000000003737213305601050015012 0ustar This is the Debian GNU/Linux prepackaged version of the Python programming language. Python was written by Guido van Rossum and others. This package was put together by Klee Dienes from sources from ftp.python.org:/pub/python, based on the Debianization by the previous maintainers Bernd S. Brentrup and Bruce Perens. Current maintainer is Matthias Klose until the final 2.3 version is released. Copyright notice (as found in LICENSE in the original source). -------------------------------------------------------------- A. HISTORY OF THE SOFTWARE ========================== Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands as a successor of a language called ABC. Guido remains Python's principal author, although it includes many contributions from others. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) in Reston, Virginia where he released several versions of the software. In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations (now Zope Corporation, see http://www.zope.com). In 2001, the Python Software Foundation (PSF, see http://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corporation is a sponsoring member of the PSF. All Python releases are Open Source (see http://www.opensource.org for the Open Source Definition). Historically, most, but not all, Python releases have also been GPL-compatible; the table below summarizes the various releases. Release Derived Year Owner GPL- from compatible? (1) 0.9.0 thru 1.2 1991-1995 CWI yes 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes 1.6 1.5.2 2000 CNRI no 2.0 1.6 2000 BeOpen.com no 1.6.1 1.6 2001 CNRI yes (2) 2.1 2.0+1.6.1 2001 PSF no 2.0.1 2.0+1.6.1 2001 PSF yes 2.1.1 2.1+2.0.1 2001 PSF yes 2.2 2.1.1 2001 PSF yes 2.1.2 2.1.1 2002 PSF yes 2.1.3 2.1.2 2002 PSF yes 2.2.1 2.2 2002 PSF yes 2.2.2 2.2.1 2002 PSF yes 2.2.3 2.2.2 2003 PSF yes 2.3 2.2.2 2002-2003 PSF yes 2.3.1 2.3 2002-2003 PSF yes 2.3.2 2.3.1 2002-2003 PSF yes 2.3.3 2.3.2 2002-2003 PSF yes 2.3.4 2.3.3 2004 PSF yes 2.3.5 2.3.4 2005 PSF yes 2.4 2.3 2004 PSF yes 2.4.1 2.4 2005 PSF yes 2.4.2 2.4.1 2005 PSF yes 2.4.3 2.4.2 2006 PSF yes 2.4.4 2.4.3 2006 PSF yes 2.5 2.4 2006 PSF yes 2.5.1 2.5 2007 PSF yes 2.5.2 2.5.1 2008 PSF yes 2.5.3 2.5.2 2008 PSF yes 2.6 2.5 2008 PSF yes 2.6.1 2.6 2008 PSF yes 2.6.2 2.6.1 2009 PSF yes 2.6.3 2.6.2 2009 PSF yes 2.6.4 2.6.3 2009 PSF yes 3.0 2.6 2008 PSF yes 3.0.1 3.0 2009 PSF yes 3.1 3.0.1 2009 PSF yes 3.1.1 3.1 2009 PSF yes Footnotes: (1) GPL-compatible doesn't mean that we're distributing Python under the GPL. All Python licenses, unlike the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible licenses make it possible to combine Python with other software that is released under the GPL; the others don't. (2) According to Richard Stallman, 1.6.1 is not GPL-compatible, because its license has a choice of law clause. According to CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 is "not incompatible" with the GPL. Thanks to the many outside volunteers who have worked under Guido's direction to make these releases possible. B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON =============================================================== PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 -------------------------------------------- 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF 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 Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 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 Python. 4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, 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 PSF and Licensee. This License Agreement does not grant permission to use PSF 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 Python, Licensee agrees to be bound by the terms and conditions of this License Agreement. BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 ------------------------------------------- BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization ("Licensee") accessing and otherwise using this software in source or binary form and its associated documentation ("the Software"). 2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared by Licensee. 3. BeOpen is making the Software available to Licensee on an "AS IS" basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 5. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 6. This License Agreement shall be governed by and interpreted in all respects by the law of the State of California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote products or services of Licensee, or any third party. As an exception, the "BeOpen Python" logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page. 7. By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions of this License Agreement. CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 --------------------------------------- 1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 ("CNRI"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 1.6.1 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, CNRI 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 Python 1.6.1 alone or in any derivative version, provided, however, that CNRI's License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) 1995-2001 Corporation for National Research Initiatives; All Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee. Alternately, in lieu of CNRI's License Agreement, Licensee may substitute the following text (omitting the quotes): "Python 1.6.1 is made available subject to the terms and conditions in CNRI's License Agreement. This Agreement together with Python 1.6.1 may be located on the Internet using the following unique, persistent identifier (known as a handle): 1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet using the following URL: http://hdl.handle.net/1895.22/1013". 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 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 Python 1.6.1. 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, 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. This License Agreement shall be governed by the federal intellectual property law of the United States, including without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia's conflict of law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python 1.6.1 that incorporate non-separable material that was previously distributed under the GNU General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License Agreement only as to issues arising under or with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between CNRI and Licensee. This License Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By clicking on the "ACCEPT" button where indicated, or by copying, installing or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement. ACCEPT CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 -------------------------------------------------- Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. py3compile, py3clean and debpython module: ========================================== Copyright © 2010-2013 Piotr Ożarowski 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. python3-defaults-3.6.7/debian/debian_defaults0000664000000000000000000000056013364124271016112 0ustar [DEFAULT] # the default python3 version default-version = python3.6 # all supported python3 versions supported-versions = python3.6 # formerly supported python3 versions old-versions = python3.1, python3.2, python3.3, python3.4, python3.5 # unsupported versions, including older versions unsupported-versions = python3.1, python3.2, python3.3, python3.4, python3.5 python3-defaults-3.6.7/debian/html.xsl0000664000000000000000000000075713305601050014550 0ustar 1 1 python3-defaults-3.6.7/debian/idle.10000664000000000000000000000473413305601050014052 0ustar .TH IDLE 1 "21 September 2004" .SH NAME \fBIDLE\fP \- An Integrated DeveLopment Environment for Python .SH SYNTAX .B idle [ \fI-dins\fP ] [ \fI-t title\fP ] [ \fIfile\fP ...] .PP .B idle [ \fI-dins\fP ] [ \fI-t title\fP ] ( \fI-c cmd\fP | \fI-r file\fP ) [ \fIarg\fP ...] .PP .B idle [ \fI-dins\fP ] [ \fI-t title\fP ] - [ \fIarg\fP ...] .SH DESCRIPTION This manual page documents briefly the .BR idle command. This manual page was written for Debian because the original program does not have a manual page. For more information, refer to IDLE's help menu. .PP .B IDLE is an Integrated DeveLopment Environment for Python. IDLE is based on Tkinter, Python's bindings to the Tk widget set. Features are 100% pure Python, multi-windows with multiple undo and Python colorizing, a Python shell window subclass, a debugger. IDLE is cross-platform, i.e. it works on all platforms where Tk is installed. .LP .SH OPTIONS .TP .B \-h .PD Print this help message and exit. .TP .B \-n .PD Run IDLE without a subprocess (see Help/IDLE Help for details). .PP The following options will override the IDLE 'settings' configuration: .TP .B \-e .PD Open an edit window. .TP .B \-i .PD Open a shell window. .PP The following options imply \-i and will open a shell: .TP .B \-c cmd .PD Run the command in a shell, or .TP .B \-r file .PD Run script from file. .PP .TP .B \-d .PD Enable the debugger. .TP .B \-s .PD Run $IDLESTARTUP or $PYTHONSTARTUP before anything else. .TP .B \-t title .PD Set title of shell window. .PP A default edit window will be bypassed when \-c, \-r, or \- are used. .PP [arg]* and [file]* are passed to the command (\-c) or script (\-r) in sys.argv[1:]. .SH EXAMPLES .TP idle .PD Open an edit window or shell depending on IDLE's configuration. .TP idle foo.py foobar.py .PD Edit the files, also open a shell if configured to start with shell. .TP idle \-est "Baz" foo.py .PD Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell window with the title "Baz". .TP idle \-c "import sys; print sys.argv" "foo" .PD Open a shell window and run the command, passing "\-c" in sys.argv[0] and "foo" in sys.argv[1]. .TP idle \-d \-s \-r foo.py "Hello World" .PD Open a shell window, run a startup script, enable the debugger, and run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in sys.argv[1]. .TP echo "import sys; print sys.argv" | idle - "foobar" .PD Open a shell window, run the script piped in, passing '' in sys.argv[0] and "foobar" in sys.argv[1]. .SH SEE ALSO python(1). .SH AUTHORS Various. python3-defaults-3.6.7/debian/idle.desktop0000664000000000000000000000041513306600072015357 0ustar [Desktop Entry] Name=IDLE Comment=Integrated DeveLopment Environment for Python3 Exec=/usr/bin/idle %F TryExec=/usr/bin/idle Icon=/usr/share/pixmaps/idle.xpm Terminal=false Type=Application Categories=Application;Development; StartupNotify=true MimeType=text/x-python; python3-defaults-3.6.7/debian/idle.lintian-overrides0000664000000000000000000000002213305601050017332 0ustar menu-icon-missing python3-defaults-3.6.7/debian/idle.py0000775000000000000000000000013413305601050014333 0ustar #! /usr/bin/python3 from idlelib.pyshell import main if __name__ == '__main__': main() python3-defaults-3.6.7/debian/py3versions0000775000000000000000000000015513305601050015276 0ustar #! /usr/bin/python3 import sys sys.path[0:0] = ['/usr/share/python3'] import py3versions py3versions.main() python3-defaults-3.6.7/debian/py3versions.10000664000000000000000000000277713305601050015446 0ustar .TH PY3VERSIONS .SH NAME py3versions \- print python3 version information .SH SYNOPSIS .PP .B py3versions .I [-h] [-v] [] .SH DESCRIPTION .PP .B py3versions prints information about installed, supported python3 runtimes, the default runtime, and parses the information of the PythonVersion fields in the package control file for Python3. .SH OPTIONS .TP .I -d, --default Show the default python3 version. .TP .I -s, --supported Show the supported python3 versions. List is lowest version to highest version with the default version last (e.g. python3.4 python3.6 python3.5 if python3.4, 3.5, and 3.6 are supported, but python3.5 is the default python3). .TP .I -r, --requested [|] Reads the value of the .B X-Python3-Version field in the source section of a control file and shows all matching python3 versions. The parameter is interpreted as a version string, if it is not the name of a file. If the X-Python3-Version field is missing, it will fall back to list the supported Python3 versions after checking debian/control. Versions less than 3 are ignored. The keyword all is ignored because it covers all Python2 versions. The former keyword current is not supported at all in Python3. Uses the same sort order as the -s, --supported option. .TP .I -i, --installed Show the installed supported python3 versions. .TP .I -v, --version Limit the output to the version numbers of the python3 versions. .TP .I -h, --help Print a help text. .SH SEE ALSO Python policy. .SH AUTHOR Matthias Klose python3-defaults-3.6.7/debian/py3versions.py0000664000000000000000000002670513305601050015733 0ustar #! /usr/bin/python3 import os import re import sys _defaults = None _old_versions = None _unsupported_versions = None _supported_versions = ["python%s" % ver.strip() for ver in os.environ.get('DEBPYTHON3_SUPPORTED', '').split(',') if ver.strip()] #_default_version = "python%s" % os.environ.get('DEBPYTHON3_DEFAULT', '') #if _default_version == 'python': # _default_version = None _default_version = None def read_default(name=None): global _defaults from configparser import ConfigParser, NoOptionError if not _defaults: if os.path.exists('/usr/share/python3/debian_defaults'): config = ConfigParser() defaultsfile = open('/usr/share/python3/debian_defaults') config.read_file(defaultsfile) defaultsfile.close() _defaults = config if _defaults and name: try: value = _defaults.get('DEFAULT', name) except NoOptionError: raise ValueError return value return None def parse_versions(vstring): if len(vstring.split(',')) > 2: raise ValueError('too many arguments provided for X-Python3-Version: min and max only.') import operator operators = {None: operator.eq, '=': operator.eq, '>=': operator.ge, '<=': operator.le, '<<': operator.lt} vinfo = {} exact_versions = set() version_range = set(supported_versions(version_only=True)) relop_seen = False for field in vstring.split(','): field = field.strip() if field == 'all': continue if field in ('current', 'current_ext'): continue vinfo.setdefault('versions', set()) ve = re.compile(r'(>=|<=|<<|=)? *(\d\.\d)$') m = ve.match(field) try: if not m: raise ValueError('error parsing Python3-Version attribute') op, v = m.group(1), m.group(2) vmaj, vmin = v.split('.') if int(vmaj) < 3: continue if op in (None, '='): exact_versions.add(v) else: relop_seen = True filtop = operators[op] version_range = [av for av in version_range if filtop(av, v)] except Exception: raise ValueError('error parsing Python3-Version attribute') if 'versions' in vinfo: vinfo['versions'] = exact_versions if relop_seen: vinfo['versions'] = exact_versions.union(version_range) return vinfo def old_versions(version_only=False): global _old_versions if not _old_versions: try: value = read_default('old-versions') _old_versions = [s.strip() for s in value.split(',')] except ValueError: _old_versions = [] if version_only: return [v[6:] for v in _old_versions] else: return _old_versions def unsupported_versions(version_only=False): global _unsupported_versions if not _unsupported_versions: try: value = read_default('unsupported-versions') _unsupported_versions = [s.strip() for s in value.split(',')] except ValueError: _unsupported_versions = [] if version_only: return [v[6:] for v in _unsupported_versions] else: return _unsupported_versions def supported_versions(version_only=False): global _supported_versions,_default_version default_version() if not _supported_versions: try: value = read_default('supported-versions') _supported_versions = [s.strip() for s in value.split(',')] except ValueError: cmd = ['/usr/bin/apt-cache', '--no-all-versions', 'show', 'python3-all'] try: import subprocess p = subprocess.Popen(cmd, bufsize=1, shell=False, stdout=subprocess.PIPE) fd = p.stdout except ImportError: fd = os.popen(' '.join(cmd)) depends = None for line in fd: if line.startswith('Depends:'): depends = line.split(':', 1)[1].strip().split(',') fd.close() depends = [re.sub(r'\s*(\S+)[ (]?.*', r'\1', s) for s in depends] _supported_versions = depends default = _supported_versions.pop(_supported_versions.index(_default_version)) _supported_versions.sort() _supported_versions.append(default) if version_only: return [v[6:] for v in _supported_versions] else: return _supported_versions def default_version(version_only=False): global _default_version if not _default_version: _default_version = os.readlink('/usr/bin/python3') # consistency check debian_default = read_default('default-version') if not _default_version in (debian_default, os.path.join('/usr/bin', debian_default)): raise ValueError("the symlink /usr/bin/python3 does not point to the " "python3 default version. It must be reset " "to point to %s" % debian_default) _default_version = debian_default if version_only: return _default_version[6:] else: return _default_version def requested_versions(vstring, version_only=False): global _default_version default_version() versions = None vinfo = parse_versions(vstring) supported = supported_versions(version_only=True) if len(vinfo) == 1: versions = vinfo['versions'].intersection(supported) vl = [] for version in versions: vl.append(version) try: default = vl.pop(vl.index(_default_version[6:])) except: default = '' vl.sort() if default: vl.append(default) else: raise ValueError('No supported python3 versions in version string') if not versions: raise ValueError('empty set of versions') if version_only: return vl else: return ['python%s' % v for v in vl] def installed_versions(version_only=False): import glob supported = supported_versions() versions = [os.path.basename(s) for s in glob.glob('/usr/bin/python3.[0-9]') if os.path.basename(s) in supported] versions.sort() if version_only: return [v[6:] for v in versions] else: return versions class ControlFileValueError(ValueError): pass class MissingVersionValueError(ValueError): pass def extract_pyversion_attribute(fn, pkg): """read the debian/control file, extract the X-Python3-Version field.""" version = None sversion = None section = None with open(fn, encoding='utf-8') as controlfile: lines = [line.strip() for line in controlfile] for line in lines: if line == '' and section != None: if pkg == 'Source': break section = None elif line.startswith('Source:'): section = 'Source' elif line.startswith('Package: ' + pkg): section = pkg elif line.lower().startswith('x-python3-version:'): if section != 'Source': raise ValueError('attribute X-Python3-Version not in Source section') sversion = line.split(':', 1)[1].strip() if section is None: raise ControlFileValueError('not a control file') if pkg == 'Source': if sversion is None: raise MissingVersionValueError('no X-Python3-Version in control file') return sversion return version ''' def requested_versions_bis(vstring, version_only=False): versions = [] py_supported_short = supported_versions(version_only=True) for item in vstring.split(','): v=item.split('-') if len(v)>1: if not v[0]: v[0] = py_supported_short[0] if not v[1]: v[1] = py_supported_short[-1] for ver in py_supported_short: try: if version_cmp(ver,v[0]) >= 0 \ and version_cmp(ver,v[1]) <= 0: versions.append(ver) except ValueError: pass else: if v[0] in py_supported_short: versions.append(v[0]) versions.sort(version_cmp) if not versions: raise ValueError('empty set of versions') if not version_only: versions=['python'+i for i in versions] return versions ''' def main(): from optparse import OptionParser usage = '[-v] [-h] [-d|--default] [-s|--supported] [-i|--installed] ' '[-r|--requested |]' parser = OptionParser(usage=usage) parser.add_option('-d', '--default', help='print the default python3 version', action='store_true', dest='default') parser.add_option('-s', '--supported', help='print the supported python3 versions', action='store_true', dest='supported') parser.add_option('-r', '--requested', help='print the python3 versions requested by a build; ' 'the argument is either the name of a control file ' 'or the value of the X-Python3-Version attribute', action='store_true', dest='requested') parser.add_option('-i', '--installed', help='print the installed supported python3 versions', action='store_true', dest='installed') parser.add_option('-v', '--version', help='print just the version number(s)', default=False, action='store_true', dest='version_only') opts, args = parser.parse_args() program = os.path.basename(sys.argv[0]) if opts.default and len(args) == 0: try: print(default_version(opts.version_only)) except ValueError as msg: print("%s:" % program, msg) sys.exit(1) elif opts.supported and len(args) == 0: print(' '.join(supported_versions(opts.version_only))) elif opts.installed and len(args) == 0: print(' '.join(installed_versions(opts.version_only))) elif opts.requested and len(args) <= 1: if len(args) == 0: versions = 'debian/control' else: versions = args[0] try: if os.path.isfile(versions): fn = versions try: vstring = extract_pyversion_attribute(fn, 'Source') vs = requested_versions(vstring, opts.version_only) except ControlFileValueError: sys.stderr.write("%s: not a control file: %s, " % (program, fn)) sys.exit(1) except MissingVersionValueError: sys.stderr.write("%s: no X-Python3-Version in control " "file, using supported versions\n" % program) vs = supported_versions(opts.version_only) else: vs = requested_versions(versions, opts.version_only) print(' '.join(vs)) except ValueError as msg: sys.stderr.write("%s: %s\n" % (program, msg)) sys.exit(1) else: sys.stderr.write("usage: %s %s\n" % (program, usage)) sys.exit(1) if __name__ == '__main__': main() python3-defaults-3.6.7/debian/python-policy.dbk0000664000000000000000000013662013152176723016371 0ustar Debian Python Policy Neil Schemenauer nas@debian.org Matthias Klose doko@debian.org Gregor Hoffleit flight@debian.org Josselin Mouette joss@debian.org Joe Wreschnig piman@debian.org Loïc Minier lool@debian.org Scott Kitterman scott@kitterman.com Barry Warsaw barry@debian.org Ben Finney ben+debian@benfinney.id.au version 0.10.1.1 This document describes the packaging of Python within the Debian GNU/Linux distribution and the policy requirements for packaged Python programs and modules. 1999 2016Software in the Public Interest This manual 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 2 of the License, or (at your option) any later version. This 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. A copy of the GNU General Public License version 2 is available as /usr/share/common-licences/GPL-2 in the Debian GNU/Linux system, or on the World Wide Web at GNU General Public License, version 2. You can also obtain it by writing to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. On the move to Python 3 Debian currently supports two Python stacks, one for Python 3 and one for Python 2. The long term goal for Debian is to reduce this to one stack, dropping the Python 2 stack at some time. PEP 404 states that no more major Python 2 releases are planned, although the latest released minor version 2.7 will see some extended support, documented in PEP 466. Packages in Debian should use Python 3 if Python 3 is supported. New packages should use Python 3 from the initial upload, new upstream versions for existing packages should use Python 3 if the new upstream version supports it. Programs should use Python 3, and should not be packaged for Python 2 as well. Python 3 should be used for the packaging if the packaging scripts use Python. Python libraries, if they support Python 3, should be always packaged for Python 3. If an application supports only Python 2, the Python libraries for that application should also be packaged for Python 2. Existing Python 2 libraries should not be dropped before the last reverse dependency is removed. Python Packaging
Versions At any given time, the binary package python3 will represent the current default Debian Python 3 version; the binary package python will represent the current default Debian Python 2 version. As far as is reasonable, Python 3 and Python 2 should be treated as separate runtime systems with minimal interdependencies. In some cases, Python policy explicitly references Python helper tools. For Debian Stretch, the dh-python package provides the only such tools; earlier helpers have been removed from Debian. It is a design goal to fully specify required interfaces and functions in policy for Python 3 and to avoid enshrining specific implementation details in policy. Except as noted, policy for Python 2 is the same as Python 3 with the exception of the different major version number as needed to distinguish them. The default Debian Python version, for each of Python 3 and Python 2, should always be the latest stable upstream version that can be fully integrated in Debian. There may be newer supported or unsupported versions included in Debian if they are not fully integrated for a particular release. Apart from the default version, legacy versions of Python or beta releases of future upstream versions may be included as well in Debian, as long as they are needed by other packages, or as long as it seems reasonable to provide them. Note: For the scope of this document, a Python version is synonymous with all micro versions within that minor version. e.g. Python 3.5.0 and 3.5.1 are micro versions of the same Python version 3.5, but Python 3.4 and 3.5 are indeed different versions. For any version, the main binary package must be called pythonX.Y. The set of currently supported Python 3 versions can be found in /usr/share/python3/debian_defaults; the supported interface to this information is through /usr/bin/py3versions. The set of currently supported Python 2 versions can be found in /usr/share/python/debian_defaults; the supported interface to this information is /usr/bin/pyversions. These files are in Python configparser format. They define (in the DEFAULT section) the following options: default-version: The name of the interpreter for the current default Debian Python. supported-versions: The set of interpreter names currently supported and for which modules should be built and byte-compiled. This includes default-version. old-versions: The set of interpreter names which might still be on the system but for which modules should not be built. unsupported-versions: The set of interpreter names which should not be supported at all, that is modules should not be built or byte-compiled for these. This includes (is a superset of) old-versions. Newer versions might also appear in unsupported-versions before being moved to supported-versions.
Main packages For every Python version provided in Debian, the binary package pythonX.Y shall provide a complete distribution for deployment of Python scripts and applications. The package must ensure that the binary /usr/bin/pythonX.Y is provided. Installation of pythonX.Y shall provide the modules of the upstream Python distribution with some exceptions. Excluded are modules that cannot be included for licensing reasons (for example the profile module), for dependency tracking purposes (for example the GPL-licensed gdbm module), or that should not be included for packaging reasons (for example the tk module which depends on Xorg). Some tools and files for the development of Python modules are split off in a separate binary package pythonX.Y-dev. Documentation will be provided separately as well. At any time, the python3 binary package must ensure that /usr/bin/python3 is provided, as a symlink to the current python3.Y executable. The package must depend on the python3.Y package that installs the executable. The version of the python3 package must be greater than or equal to 3.Y and lower than 3.Y+1. At any time, the python binary package must ensure that /usr/bin/python2 is provided, as a symlink to the current python2.Y executable. The package must depend on the python2.Y package that installs the executable. The version of the python package must be greater than or equal to 2.Y and lower than 2.Y+1. The python binary package must also ensure that /usr/bin/python is provided, as a symlink to the current python2.Y executable. See PEP 394 for details.
Minimal packages For every Python version provided in Debian, the binary package pythonX.Y-minimal might exist and should not be depended upon by other packages except the Python runtime packages themselves.
Python Interpreter
Interpreter Name The different Python major versions require different interpreters (see ). Python scripts that require the default Python 3 version should specify python3 as the interpreter name. Python scripts that require the default Python 2 version should specify python2 as the interpreter name. Python scripts may specify python as the interpreter name only if they do not require any particular version of Python. (Note: this means any python2 version) Python scripts that only work with a specific Python minor version must explicitly use the versioned interpreter name (pythonX.Y).
Interpreter Location Python scripts should specify the Debian Python interpreter, to ensure that the Debian Python installation is used and all dependencies on additional Python modules are met. The preferred specification for the Python 3 interpreter is /usr/bin/python3 (or /usr/bin/python3.Y if it requires Python 3.Y). The preferred specification for the Python 2 interpreter is /usr/bin/python2 (or /usr/bin/python2.Y if it requires Python 2.Y). Scripts requiring the default Python 2 version may instead specify the interpreter /usr/bin/python. Maintainers should not override the Debian Python interpreter using /usr/bin/env name. This is not advisable as it bypasses Debian's dependency checking and makes the package vulnerable to incomplete local installations of Python.
Module Path By default, Python modules are searched in the directories listed in the PYTHONPATH environment variable and in the sys.path Python variable. For all supported Debian releases, sys.path does not include a /usr/lib/pythonXY.zip entry. Directories with private Python modules must be absent from the sys.path. Public Python 3 modules must be installed in the system Python 3 modules directory, /usr/lib/python3/dist-packages. Public Python 2 modules must be installed in the system Python 2 modules directory /usr/lib/python2.Y/dist-packages, where 2.Y is the Python 2 version. A special directory is dedicated to public Python modules installed by the local administrator, /usr/lib/python3/dist-packages for all Python 3 versions, /usr/local/lib/python2.Y/dist-packages for Python 2. For local installation of Python modules by the system administrator, special directories are reserved. The directory /usr/local/lib/python3/site-packages is in the Python 3 runtime module search path. The directory /usr/local/lib/python2.Y/site-packages is in the Python 2.Y runtime module search path. Additional information on appending site-specific paths to the module search path is available in the official documentation of the site module. Python modules which work with multiple supported Python 2 versions must install to version-specific locations, for instance /usr/lib/python2.6/dist-packages/foo.py and /usr/lib/python2.7/dist-packages/foo.py. These should point to a common file. Architecture-independent public Python 3 modules must be installed to /usr/lib/python3/dist-packages. Architecture-independent public Python 2 modules should be installed to /usr/lib/python2.7/dist-packages. The historical location for this was /usr/share/pyshared. Since Python 2.7 is the last Python 2 version and the only supported version in Wheezy and later releases, a version-specific location is sufficient.
Hooks for updates to installed runtimes The python binary package has special hooks to allow other packages to act upon updates to the installed runtimes. This mechanism is required to handle changes of the default Python runtime in some packages and to enable the Python packaging helpers. There are three supported hook types which come in the form of scripts which are invoked from the maintainer scripts of the Python runtime packages when specific installations, removals, or upgrades occur. /usr/share/python3/runtime.d/*.rtinstall, /usr/share/python/runtime.d/*.rtinstall: These are called when a runtime is installed or becomes supported. The first argument is rtinstall, the second argument is the affected runtime (for example pythonX.Y) and the third and fourth argument are the old and new version of this packaged runtime if this runtime was already installed but unsupported. /usr/share/python3/runtime.d/*.rtremove, /usr/share/python/runtime.d/*.rtremove: These are called when a runtime is removed or stops being supported. The first argument is rtremove, and the second argument is the affected runtime (for example pythonX.Y). /usr/share/python3/runtime.d/*.rtupdate, /usr/share/python/runtime.d/*.rtupdate: These are called when the default runtime changes. The first argument is either pre-rtupdate, called before changing the default runtime, or rtupdate, called when changing the default runtime, or post-rtupdate, called immediately afterwards. The second argument is the old default runtime (for example pythonX.Y), and the third argument is the new default runtime (for example pythonX.Z).
Documentation Python documentation is split out in separate binary packages pythonX.Y-doc. The binary package python3-doc will always provide the documentation for the default Debian Python 3 version. The binary package python-doc will always provide the documentation for the default Debian Python 2 version. TODO: Policy for documentation of third party packages.
Packaged Modules The goal of these policies is to reduce the work necessary for Python transitions. Python modules are internally very dependent on a specific Python version. However, we want to automate recompiling modules when possible, either during the upgrade itself (re-compiling bytecode files *.pyc and *.pyo) or shortly thereafter with automated rebuilds (to handle C extensions). These policies encourage automated dependency generation and loose version bounds whenever possible.
Types of Python Modules There are two kinds of Python modules, "pure" Python modules, and extension modules. Pure Python modules are Python source code that generally works across many versions of Python. Extensions are C code compiled and linked against a specific version of the Python runtime, and so can only be used by one version of Python. Debian Python does not link extensions to libpython (as is done in some operating systems). Symbols are resolved by /usr/bin/pythonX.Y which is not linked to libpython. Python packages are a way of structuring Python’s module namespace by using “dotted module names”. See Python's glossary for details on how packages are defined in Python terms (a package in the Python sense is unrelated to a Debian package). Python packages must be packaged into the same directory (as done by upstream). Splitting components of a package across directories changes the import order and may confuse documentation tools and IDEs. There are two ways to distribute Python modules. Public modules are installed in a public directory as listed in . They are accessible to any program. Private modules are installed in a private directory such as /usr/share/package-name or /usr/lib/package-name. They are generally only accessible to a specific program or suite of programs included in the same package.
Wheels PEP 427 defines a built-package format called "wheels", which is a Zip format archive containing Python code and a *.dist-info metadata directory, in a single file named with the .whl suffix. As Zip files, wheels containing pure Python can be put on sys.path and modules in the wheel can be imported directly by Python's import statement. (Importing extension modules from wheels is not yet supported as of Python 3.4.) Except as described below, packages must not build or provide wheels. They are redundant to the established way of providing Python libraries to Debian users, take no advantage of distro-based tools, and are less convenient to use. E.g. they must be explicitly added to sys.path, cannot be easily grepped, and stack traces through Zip files are more difficult to debug. A very limited set of wheel packages are available in the archive, but these support the narrow purpose of enabling the pip, virtualenv, and pyvenv tools in a Debian policy compliant way. These packages build their own dependent wheels through the use of the dirtbike "rewheeling" tool, which takes installed Debian packages and turns them back into wheels. Only universal wheels (i.e. pure-Python, Python 3 and 2 compatible packages) are supported. Since only the programs that require wheels need build them, only they may provide -whl packages, e.g. python3-pip-whl. When these binary packages are installed, *.whl files must be placed in the /usr/share/python-wheels directory. The location inside a virtual environment will be rooted in the virtual environment, instead of /usr.
Module Package Names Public Python modules must be packages separately by major Python version, to preserve run time separation between Python 2 and Python 3. Public Python 3 modules used by other packages must have their binary package name prefixed with python3-. Public Python 2 modules used by other packages must have their binary package name prefixed with python-. It is recommended to use this prefix for all packages with public modules as they may be used by other packages in the future. The binary package for module foo should preferably be named python3-foo (for Python 3) or python-foo (for Python 2), if the module name allows. This is not required if the binary package installs multiple modules, in which case the maintainer shall choose the name of the module which best represents the package. For subpackages such as foo.bar, the recommendation is to name the binary package python3-foo.bar (for Python 3) or python-foo.bar (for Python 2). Such a package should support the current Debian Python version, and more if possible (there are several tools to help implement this, see ). For example, if Python 3.3, 3.4, and 3.5 are supported, the Python statement import foo should import the module when the program interpreter is any of /usr/bin/python3.3, /usr/bin/python3.4, and /usr/bin/python3.5. This requirement also applies to extension modules; binaries for all the supported Python versions should be included in a single package. Packages intended for use with Django (python3-django/ python-django) are installed in the same namespace as other python packages for a variety of reasons. Many such packages are named django_$name upstream. These are then packaged as python3-django-$name and python-django-$name. This makes it clear that they are intended for use with Django and not general purpose Python modules. Debian maintainers are encouraged to work with their upstreams to support consistent use of this approach.
Specifying Supported Versions The debian/control source paragraph may contain optional fields to specify the versions of Python the package supports. The optional X-Python3-Version field specifies the versions of Python 3 supported. When not specified, it defaults to all currently supported Python 3 versions. Similarly, the optional fields X-Python-Version or XS-Python-Version were used to specify the versions of Python 2 supported by the source package. They are obsolete and can be removed now that only Python 2.7 is supported. These fields are used by some packaging scripts to automatically generate appropriate Depends and Provides lines. The format of the field may be one of the following: X-Python3-Version: >= X.Y X-Python3-Version: >= A.B, << X.Y XS-Python-Version: A.B, X.Y XS-Python-Version: all The keyword all means that the package supports any Python 2 version available but might be deprecated in the future since using version numbers is clearer than all and encodes more information. The keyword all is limited to Python 2 versions and must be ignored for Python 3 versions. A comma-separated list of multiple individual versions (e.g. 3.3, 3.4, 3.5) in XS-Python-Version will continue to be supported, but is not recommended. The use of multiple individual versions in X-Python-Version or X-Python3-Version is not supported for Wheezy and later releases. The keyword current has been deprecated and used to mean that the package would only have to support a single Python 2 version (even across default version changes). It must be ignored for Python 3 versions. The use of XB-Python-Version in the binary package paragraphs of debian/control file has been deprecated and should be removed in the normal course of package updates. It never achieved sufficient deployment to support its intended purpose of managing Python transitions. This purpose can be adequately accomplished by examining package dependencies.
Dependencies Any package that installs modules for the default Python version (or many versions including the default) as described in , must declare a dependency on the default Python runtime package. If it requires other modules to work, the package must declare dependencies on the corresponding packaged modules. The package must not declare dependency on any version-specific Python runtime or module package. For Python 3, the correct dependencies are Depends: python3 (>= 3.Y) and any corresponding python3-foo packages. For Python 2, the correct dependencies are Depends: python (>= 2.Y) and any corresponding python-foo packages. Any package that installs Python modules or Python 3 binary extensions must also declare a maximum version it supports as currently built. This is accomplished by declaring a maximum version constraint strictly less than one higher than the current maximum version, i.e. Depends: python3 (<< X.Y).
Provides Binary packages that declare Provides dependencies of the form pythonX.Y-foo were never supported for Python 3 and are no longer useful for Python 2. They should be removed in the normal course of package updates. Future provision of values for the substituation variable python:Provides is not guaranteed.
Modules Byte-Compilation If a binary package provides any binary-independent modules (foo.py files), the corresponding byte-compiled modules (foo.pyc files) and optimized modules (foo.pyo files) must not ship in the package. Instead, they should be generated in the package's post-install script, and removed in the package's pre-remove script. The package's prerm has to make sure that both foo.pyc and foo.pyo are removed. A binary package should only byte-compile the files which belong to the package. The file /etc/python/debian_config allows configuration how modules should be byte-compiled. The post-install scripts should respect these settings. Pure Python modules in private installation directories that are byte-compiled with the default Python version must be forcefully byte-compiled again when the default Python version changes. Public Python extensions should be bin-NMUed. Private Python extensions should be subject to binary NMUs every time the default interpreter changes, unless the extension is updated through a *.rtupdate script.
Python Programs
Interpreter directive (“Shebang”) Executables written for interpretation by Python must use an appropraite interpreter directive, or “shebang”, as the first line of the program. This line should be of the form #!interpreter_location. See for the interpreter name to use. As noted in , the form #!/usr/bin/env interpreter_name is deprecated.
Programs using the default Python A package that installs a program that can be run by any version of Python 3 must declare a dependency on python3, with a versioned dependency if necessary. A package that installs a program that can be run by any version of Python 2 must declare a dependency on python2, with a versioned dependency if necessary. If the program needs the public Python module foo, the package must depend on the binary package that installs the foo module. See for the naming of packages that install public Python modules.
Programs Shipping Private Modules A program that specifies python3 or python as its interpreter may require its own private Python modules. These modules should be installed in /usr/share/module, or /usr/lib/module if the modules are architecture-dependent (e.g. extensions). The rules explained in apply to those private modules: the byte-compiled modules must not be shipped with the binary package, they should be generated in the package's post-install script using the current default Python version, and removed in the pre-remove script. Modules should be byte-compiled using the current default Python version. Programs that have private compiled extensions must either handle multiple version support themselves, or declare a tight dependency on the current Python version (e.g. Depends: python3 (>= 3.5), python3 (<< 3.6).
Programs Using a Particular Python Version A program which requires a specific minor version of Python must specify the versioned interpreter pythonX.Y. The package that installs the programs must also specify a dependency on pythonX.Y and on any packages that install necessary modules. The notes on installation directories and byte-compilation for programs that support any version of Python also apply to programs supporting only a single Python version. Modules to be byte-compiled should use the same Python version as the package itself.
Programs Embedding Python
Building Embedded Programs Any package that installs a program which embeds a Python interpreter must declare Build-Depends on pythonX.Y-dev, where X.Y is the Python version the program builds against. It should be the current default Python version unless the program does not work correctly with this version.
Embedded Python Dependencies Dependencies for programs linking against the shared Python library will be automatically created by dpkg-shlibdeps. The libpythonX.Y.so.Z library the program is built against is provided by the pythonX.Y package.
Interaction with Locally Installed Python Versions As long as you don't install other versions of Python in your path, Debian's Python versions won't be affected by a new version. If you install a different micro version of the version of Python you have got installed, you will need to be careful to install all the modules you use for that version of Python too. Build Dependencies Build dependencies for Python-dependent packages must be declared for every Python version that the package is built for. The python3-all-dev should be used when building extensions for any or all Python 3 versions. The python-all-dev should be used when building extensions for any or all Python 2 versions. To build for a specific version or versions, declare Build-Depends on pythonX.Y-dev. Some applications and pure Python modules may be able to avoid dependency on the -dev packages, and declare Build-Depends on the runtime environment only (python3, python3-all, python, python-all). A package that does not require the -dev packages must not declare Build-Depends on them. Declare Build-Depends on at least: Build-Depends: python2.7 Build-Depends: python2.6 (>= 2.6-1) Build-Depends: python (>= 2.6.6-9) Build-Depends: python-all Build-Depends: python2.7-dev Build-Depends: python3.5-dev (>= 3.5.1-1) Build-Depends: python-dev (>= 2.6.6-9) Build-Depends: python-all-dev Build-Depends: python3-all-dev (>= 3.2) Packaging Tools This section describes the various tools to help package Python programs and modules for Debian. Although none of these tools are mandatory, their use is strongly encouraged, as the above policy has been designed with them in mind (and vice versa). This appendix is just an overview. If you use these tools, you should read their full documentation.
distutils The standard Python distutils module has been modified in Debian to change the default installation directory of public Python modules and to add a new flag to the install command to override the default, --install-layout=. Public Python modules installed with a modified distutils default to /usr/local/lib/pythonX.Y/dist-packages for Python 2.6 and later. This directory is seen by the system-provided Python 2.6. When using a local Python installation, the default is /usr/local/lib/pythonX.Y/site-packages which is only seen by the local Python installation. Using the --install-layout=deb flag to the install command of setup.py with a system-provided Python 2.6 or later versions, Python modules will be installed to /usr/lib/pythonX.Y/dist-packages which is only seen by the system-provided Python, not by a local installation.
setuptools The related Python setuptools module has been modified in Debian along the same lines as distutils. Upstream focus on developments and improvements for Python packaging tools has largely shifted away from distutils and to setuptools. They offer a similar API and at some point in the future, setuptools may fully replace distutils in Debian package builds.
<literal>dh-python</literal> dh-python provides extensions for debhelper to make it easier to package Python modules and extensions. They calculate Python dependencies, add maintainer scripts to byte compile files, etc. Their use is not mandatory, but they are recommended by the Debian Python maintainers. See man dh_python3 or man dh_python2 for details.
pybuild Pybuild is a Debian Python specific build system that invokes various build systems for requested Python versions in order to build modules and extensions. It supports automatically building for multiple Python versions.
CDBS The CDBS python-distutils.mk class helps packaging of distutils based Python packages.
<literal>python-support</literal> (removed) python-support provided another way to manage Python modules. It has been removed from Debian Stretch and later releases.
<literal>python-central</literal> (removed) python-central provided another way to manage Python modules. It has been removed from Debian Jessie and later releases.
Upgrade Procedure This section describes the procedure for the upgrade when the default Python version is changed in the Debian unstable release, requiring recompilation of many Python-related packages. Selected pre-releases and release candidates of new Python versions are uploaded to Debian experimental to support pre-transition work and testing. Application and module maintainers make sourceful changes where needed to prepare for the new Python version when needed. Have a long and heated discussion. The Debian Python maintainer and module/application maintainers discuss the readiness for a new default Debian Python version and associated packaging/policy changes. Once there is some consensus, the Python maintainer announces the upgrade and uploads to unstable. Upload of the Python core meta-packages python, python-dev, python-doc and several python-module, depending on the new pythonX.Y, pythonX.Y-dev and so on. The Debian release team schedules rebuilds for packages that may need it. Packages that require additional manual work get updated and uploaded. The necessary package builds are typcially done in three phases in order to keep transitions as smooth as possible. For Python 3, there is no general need to update architecture all packages for a new Python 3 version. Only architecture any packages need to be rebuilt. The new Python 3 version is added to supported versions and packages that support multiple Python 3 versions are binNMUed. They now support both the new and older Python 3 versions. This requires transition assistance from the release team in the form of a transition tracker and binNMU scheduling, but is not a transition that can cause entanglements with other transitions in Debian. Once the default Python 3 version is changed, binNMUs are done for packages that only support one Python 3 version. Some transient uninstallability is unavoidable. This is a transition that can entangle other transitions in Debian and requires more careful coordination with the release team. After the old Python 3 version is dropped from supported versions then packages with multi-version support are binNMUed again to remove support for the old Python 3 version. This is not a true transition and only needs a tracker and binNMU scheduling.
python3-defaults-3.6.7/debian/python.doc-base.python-policy0000664000000000000000000000116213305601050020600 0ustar Document: python-policy Title: Debian Python Policy (Proposal) Author: Neil Schemenauer, Matthias Klose, Gregor Hoffleit Abstract: This document describes the packaging of Python within the Debian GNU/Linux distribution and the policy requirements for packaged Python programs and modules. . The Debian Python Policy has still a draft status. Section: Debian Format: docbook-xml Files: /usr/share/doc/python/python-policy.dbk.gz Format: text Files: /usr/share/doc/python/python-policy.txt.gz Format: HTML Index: /usr/share/doc/python/python-policy.html/index.html Files: /usr/share/doc/python/python-policy.html/*.html python3-defaults-3.6.7/debian/python.mk0000664000000000000000000000415613305601050014723 0ustar # some macros useful for packaging python packages # to include it unconditionally: # include /usr/share/python3/python.mk # # to include it conditionally, and have the packaging working with earlier releases # and backports: # -include /usr/share/python/python.mk # ifeq (,$(py_sitename)) # py_sitename = site-packages # py_libdir = /usr/lib/python$(subst python,,$(1))/site-packages # py_sitename_sh = $(py_sitename) # py_libdir_sh = $(py_libdir) # endif # py_sitename: name of the site-packages/dist-packages directory depending # on the python version. Call as: $(call py_sitename, ). # Don't use this in shell snippets inside loops. py_sitename = $(if $(filter $(subst python,,$(1)), 2.3 2.4 2.5),site,dist)-packages # py_libdir: absolute path to the default python library for third party # stuff. Call as: $(call py_libdir, ). # Don't use this in shell snippets inside loops. py_libdir = /usr/lib/python$(strip $(if $(findstring 3.,$(subst python,,$(1))),3,$(subst python,,$(1))))/$(py_sitename) # py_pkgname: package name corresponding to the python version. # Call as: $(call py_pkgname, , ). py_pkgname = $(if $(findstring 3.,$(2)),$(subst python-,python3-,$(1)),$(1)) # distutils' build directory py_builddir = $(shell python$(strip $(subst python,,$(1))) -c 'from distutils.command.build import build; from distutils.core import Distribution; b = build(Distribution()); b.finalize_options(); print(b.build_platlib)') # The same macros for use inside loops in shell snippets py_sitename_sh = $$(basename $$(_py_=$(strip $(1)); python$${_py_\#python*} -c 'from distutils import sysconfig; print(sysconfig.get_python_lib())')) py_libdir_sh = $$(_py_=$(strip $(1)); python$${_py_\#python*} -c 'from distutils import sysconfig; print(sysconfig.get_python_lib())') py_builddir_sh = $$(_py_=$(strip $(1)); python$${_py_\#python*} -c 'from distutils.command.build import build; from distutils.core import Distribution; b = build(Distribution()); b.finalize_options(); print(b.build_platlib)') # Arguments to pass to setup.py install py_setup_install_args = --install-layout=deb python3-defaults-3.6.7/debian/python3-minimal.manpages0000664000000000000000000000003013305601050017601 0ustar py3clean.1 py3compile.1 python3-defaults-3.6.7/debian/python3-minimal.postinst.in0000664000000000000000000000020013305601050020275 0ustar #! /bin/sh set -e if which py3compile >/dev/null 2>&1; then py3compile -p python3-minimal /usr/share/python3/ fi #DEBHELPER# python3-defaults-3.6.7/debian/python3-minimal.prerm0000664000000000000000000000016713305601050017146 0ustar #! /bin/sh set -e rm -rf /usr/share/python3/__pycache__ rm -rf /usr/share/python3/debpython/__pycache__ #DEBHELPER# python3-defaults-3.6.7/debian/python3.desktop0000664000000000000000000000021313305601050016036 0ustar [Desktop Entry] Type=KonsoleApplication Name=Python3 Interpreter Comment=Python3 Exec=/usr/bin/python3 Icon=/usr/share/pixmaps/python3.xpm python3-defaults-3.6.7/debian/python3.lintian-overrides0000664000000000000000000000013313305601050020024 0ustar # this is the only package that can depend on it python3 binary: depends-on-python-minimal python3-defaults-3.6.7/debian/python3.postinst.in0000664000000000000000000000242113305601050016660 0ustar #! /bin/sh set -e new_config_file() { cat > /etc/python3/debian_config <<-EOF [DEFAULT] # how to byte-compile (comma separated: standard, optimize) byte-compile = standard EOF } case "$1" in configure) [ -d /etc/python3 ] || mkdir /etc/python3 [ -f /etc/python3/debian_config ] || new_config_file oldv=$(echo $2 | sed 's/^\(...\).*/\1/') if [ "$DEBIAN_FRONTEND" != noninteractive ]; then echo "running python rtupdate hooks for @PVER@..." fi for hook in /usr/share/python3/runtime.d/*.rtupdate; do [ -x $hook ] || continue if ! $hook rtupdate python$oldv @PVER@; then hb=$(basename $hook .rtupdate) echo >&2 "error running python rtupdate hook $hb" errors=yes fi done [ -z "$errors" ] || exit 4 if [ "$DEBIAN_FRONTEND" != noninteractive ]; then echo "running python post-rtupdate hooks for @PVER@..." fi for hook in /usr/share/python3/runtime.d/*.rtupdate; do [ -x $hook ] || continue if ! $hook post-rtupdate python$oldv @PVER@; then hb=$(basename $hook .rtupdate) echo >&2 "error running python post-rtupdate hook $hb" errors=yes fi done [ -z "$errors" ] || exit 5 esac if which py3compile >/dev/null 2>&1; then py3compile -p python3 /usr/share/python3/ fi #DEBHELPER# python3-defaults-3.6.7/debian/python3.postrm.in0000664000000000000000000000012213305601050016315 0ustar #! /bin/sh set -e case "$1" in purge) rm -rf /etc/python3 esac #DEBHELPER# python3-defaults-3.6.7/debian/python3.preinst.in0000664000000000000000000000150213305601050016460 0ustar #! /bin/sh set -e # remove the python3 alternatives before installing our own python3 link update-alternatives --auto /usr/bin/python3 >/dev/null 2>&1 || true [ -L /usr/share/doc/python3/html ] || rm -rf /usr/share/doc/python3/html case "$1" in upgrade) oldv=$(echo $2 | sed 's/^\(...\).*/\1/') if [ "$DEBIAN_FRONTEND" != noninteractive ]; then echo "running python pre-rtupdate hooks for @PVER@..." fi for hook in /usr/share/python3/runtime.d/*.rtupdate; do [ -x $hook ] || continue if ! $hook pre-rtupdate python$oldv @PVER@; then hb=$(basename $hook .rtupdate) echo >&2 "error running python pre-rtupdate hook $hb" echo >&2 "running python failed-pre-rtupdate hook $hb" $hook failed-pre-rtupdate python$oldv @PVER@ errors=yes break fi done [ -z "$errors" ] || exit 3 esac #DEBHELPER# python3-defaults-3.6.7/debian/python3.prerm0000664000000000000000000000014013305601050015511 0ustar #! /bin/sh set -e if which py3clean >/dev/null 2>&1; then py3clean -p python3 fi #DEBHELPER# python3-defaults-3.6.7/debian/rules0000775000000000000000000003523113364125753014147 0ustar #!/usr/bin/make -f # Sample debian/rules that uses debhelper. GNU copyright 1997 by Joey Hess. export SHELL = /bin/bash # Uncomment this to turn on verbose mode. #export DH_VERBOSE=1 include /usr/share/dpkg/architecture.mk changelog_values := $(shell dpkg-parsechangelog \ | awk '/^(Version|Source):/ {print $$2}') PKGSOURCE := $(word 1, $(changelog_values)) PKGVERSION := $(word 2, $(changelog_values)) UPSTRVER := $(shell echo $(PKGVERSION) | sed -rne 's,(.*)-.*,\1,p') IPKGVER := $(shell echo $(PKGVERSION) | sed -rne 's,(.*)\+.*,\1,p') VER := $(shell echo $(PKGVERSION) | sed -rne 's,(.{3}).*,\1,p') NVER := $(shell echo $(VER) | awk 'BEGIN{FS="." }{print $$1 "." $$2 + 1}') distribution := $(shell dpkg-vendor --query Vendor) distrelease := $(shell lsb_release -cs) # requiered python3.x version UPSTRVER := 3.6.7-1~ # required versions of python3-lib2to3 and python3-distutils STDLIBVER := 3.6.7-1~ ifeq (,$(filter $(distrelease),lenny etch squeeze wheezy lucid maverick natty oneiric precise quantal raring saucy trusty)) bd_i586 = dpkg-dev (>= 1.17.11), python3.6 (>= 3.6.7-1~), else bd_i586 = dpkg-dev (>= 1.16.1~), endif PWD := $(shell pwd) d := debian/tmp scriptdir = usr/share/lib/python$(VER) scriptdir = usr/share/python$(VER) scriptdir = usr/lib/python$(VER) rst2html = rst2html with_doc = yes ifneq ($(with_doc),yes) NOPKGS = -Npython-doc endif build-arch: build build-indep: build build: stamp-build stamp-build: touch stamp-build stamp-doc-policy: xsltproc --nonet --novalid debian/html.xsl debian/python-policy.dbk \ | w3m -o display_charset=UTF-8 -cols 70 -dump -no-graph -T text/html > python-policy.txt mv -f python-policy.txt debian/ rm -rf debian/python-policy.html mkdir python-policy.html ( cd python-policy.html; xsltproc --nonet --novalid ../debian/chunk.xsl ../debian/python-policy.dbk ) mv -f python-policy.html debian/ touch stamp-doc-policy stamp-doc: stamp-doc-policy touch stamp-doc control-file: sed -e "s/@UPSTRVER@/$(UPSTRVER)/g" \ -e "s/@STDLIBVER@/$(STDLIBVER)/g" \ -e "s/@IPKGVER@/$(IPKGVER)/g" \ -e "s/@NVER@/$(NVER)/g" \ -e "s/@VER@/$(VER)/g" \ -e "s/@bd_i586@/$(bd_i586)/g" \ debian/control.tmp ifeq ($(distribution),Ubuntu) ifneq (,$(findstring ubuntu, $(PKGVERSION))) m='Ubuntu Developers '; \ sed -i "/^Maintainer:/s/\(.*\)/Maintainer: $$m\nXSBC-Original-\1/" \ debian/control.tmp endif endif [ -e debian/control ] \ && cmp -s debian/control debian/control.tmp \ && rm -f debian/control.tmp && exit 0; \ mv debian/control.tmp debian/control faqs = index general programming library extending windows gui installed get-faq: rm -rf faq mkdir faq cd faq && \ wget -nv $(foreach p,$(faqs),http://python.org/doc/faq/$(p).ht) sed 's,\<\([a-zA-Z0-9]*\.html\)\>,faq/\1,' faq/index.ht \ | awk '/^Translations$$/ {exit} {print}' > faq/FAQ.ht ( \ echo ''; \ echo 'This is a local copy of the online FAQ located at'; \ echo 'http://python.org/doc/faq.'; \ echo "The copy was fetched and generated in `date '+%B %Y'`."; \ ) >> faq/FAQ.ht rm -f faq/index.ht clean: control-file dh_testdir dh_testroot rm -f stamp-* rm -f patch-stamp* rm -f debian/python-policy.txt rm -rf debian/python-policy.html rm -f faq/*.h2 faq/*.html set -e;\ for f in debian/*.in; do \ f2=`echo $$f | sed "s,PVER,python$(VER),g;s/VER/$(VER)/g;s,\.in$$,,"`; \ if [ $$f2 != debian/control ]; then \ rm -f $$f2; \ fi; \ done rm -f debian/*.py[co] make clean dh_clean stamp-control: : # We have to prepare the various control files set -e;\ for f in debian/*.in; do \ f2=`echo $$f | sed "s,PVER,python$(VER),g;s/VER/$(VER)/g;s,\.in$$,,"`; \ if [ $$f2 != debian/control ]; then \ sed -e "s/@PVER@/python$(VER)/g;s/@VER@/$(VER)/g" \ -e "s/@PRIORITY@/$(PRIORITY)/g" \ -e "s,@SCRIPTDIR@,/$(scriptdir),g" \ <$$f >$$f2; \ fi; \ done install: build stamp-dh_python stamp-install stamp-install: stamp-build control-file stamp-control dh_testdir dh_testroot dh_installdirs dh_install ifeq (0,1) dh_installdirs usr/share/doc/python/faq set -e; \ cd faq && \ for p in *.ht; do \ p=`basename $$p .ht`; \ echo $(rst2html) $$p.ht $$p.html; \ awk 'NR > 2' $$p.ht > $$p.ht2; \ $(rst2html) $$p.ht2 $$p.html; \ mv $$p.html ../debian/python/usr/share/doc/python/faq/; \ rm -f $$p.ht2; \ done mv debian/python/usr/share/doc/python/faq/FAQ.html \ debian/python/usr/share/doc/python/ endif touch stamp-install stamp-dh_python: dh_testdir dh_testroot dh_installdirs #make check_versions DESTDIR=debian/python3 PREFIX=/usr make install-dev DESTDIR=debian/python3-minimal PREFIX=/usr make install-runtime manpages # disabled by default, run manually if you want to update it # (requires apt-file and network connection) #make dist_fallback touch $@ # Build architecture-independent files here. binary-indep: build install stamp-doc dh_testdir -i dh_testroot -i dh_installman -i ifeq ($(with_doc),yes) mkdir -p debian/python3-doc/usr/share/doc/python3 ln -sf ../python$(VER)-doc/html \ debian/python3-doc/usr/share/doc/python3/html mkdir -p debian/python3-doc/usr/share/doc/python3-doc ln -sf ../python$(VER)-doc/html \ debian/python3-doc/usr/share/doc/python3-doc/html endif : # provide the idle and idle.1 defaults mkdir -p debian/idle/usr/bin install -m 755 debian/idle.py debian/idle/usr/bin/idle mkdir -p debian/idle/usr/share/man/man1 install -m 644 debian/idle.1 debian/idle/usr/share/man/man1/idle.1 mkdir -p debian/idle/usr/share/pixmaps ln -sf python3.xpm debian/idle/usr/share/pixmaps/idle.xpm mkdir -p debian/idle/usr/share/applications cp -p debian/idle.desktop debian/idle/usr/share/applications/ : # provide the 2to3-3 a and 2to3-3.1 defaults mkdir -p debian/2to3/usr/bin install -m 755 debian/2to3.py debian/2to3/usr/bin/2to3 mkdir -p debian/2to3/usr/share/man/man1 install -m 644 debian/2to3.1 debian/2to3/usr/share/man/man1/2to3.1 # dh_installdebconf -i $(NOPKGS) dh_lintian -i dh_installdocs -i $(NOPKGS) --all debian/README.Debian dh_installchangelogs -i $(NOPKGS) for p in examples idle idle3; do \ case $$p in idle*) : ;; *) p=python3-$$p; esac; \ rm -rf debian/$$p/usr/share/doc/$$p; \ ln -sf python3 debian/$$p/usr/share/doc/$$p; \ done dh_compress -i $(NOPKGS) dh_fixperms -i $(NOPKGS) dh_installdeb -i $(NOPKGS) dh_gencontrol -i $(NOPKGS) dh_md5sums -i $(NOPKGS) dh_builddeb -i $(NOPKGS) # Build architecture-dependent files here. binary-arch: build install stamp-doc dh_testdir -a dh_testroot -a dh_installman -a : # provide the python and python.1 defaults mkdir -p debian/python3-minimal/usr/bin ln -sf python$(VER) debian/python3-minimal/usr/bin/python3 ln -sf python$(VER)m debian/python3-minimal/usr/bin/python3m mkdir -p debian/python3-minimal/usr/share/man/man1 ln -sf python$(VER).1.gz \ debian/python3-minimal/usr/share/man/man1/python3.1.gz ln -sf python$(VER)m.1.gz \ debian/python3-minimal/usr/share/man/man1/python3m.1.gz : # mkdir -p debian/python3-minimal/usr/share/python3 cp -p debian/debian_defaults \ debian/python3-minimal/usr/share/python3/ install -m 755 debian/py3versions.py \ debian/python3-minimal/usr/share/python3/ install -m 644 debian/py3versions.1 \ debian/python3-minimal/usr/share/man/man1/ dh_link -ppython3-minimal /usr/share/python3/py3versions.py /usr/bin/py3versions # mkdir debian/python-minimal/usr/share/python-central # cp -p debian/python.pycentral debian/python-minimal/usr/share/python-central/ mkdir -p debian/python3/usr/bin ln -sf pydoc$(VER) debian/python3/usr/bin/pydoc3 ln -sf pygettext$(VER) debian/python3/usr/bin/pygettext3 ln -sf pdb$(VER) debian/python3/usr/bin/pdb3 mkdir -p debian/python3/usr/share/python3 install -m 644 debian/python.mk \ debian/python3/usr/share/python3/ mkdir -p debian/python3/usr/share/man/man1 ln -sf pydoc$(VER).1.gz \ debian/python3/usr/share/man/man1/pydoc3.1.gz ln -sf pygettext$(VER).1.gz \ debian/python3/usr/share/man/man1/pygettext3.1.gz ln -sf pdb$(VER).1.gz \ debian/python3/usr/share/man/man1/pdb3.1.gz mkdir -p debian/python3/usr/share/doc/python3 cp -a debian/python-policy.{html,dbk,txt} \ debian/python3/usr/share/doc/python3/ mkdir -p debian/python3/usr/share/pixmaps ln -sf python$(VER).xpm debian/python3/usr/share/pixmaps/python3.xpm : # add symlinks to policy files mkdir -p debian/python3/usr/share/doc/python$(VER) for ext in html dbk.gz txt.gz; do \ ln -sf ../python3/python-policy.$$ext \ debian/python3/usr/share/doc/python$(VER)/python-policy.$$ext; \ done ifeq (0,1) mkdir -p debian/python3/usr/share/apps/konsole cp -p debian/python.desktop debian/python3/usr/share/apps/konsole/ endif : # provide the python3-config default mkdir -p debian/python3-dev/usr/bin ln -sf python$(VER)m-config debian/python3-dev/usr/bin/python3m-config mkdir -p debian/python3-dev/usr/share/man/man1 ln -sf python$(VER)m-config.1.gz \ debian/python3-dev/usr/share/man/man1/python3m-config.1.gz ln -sf python$(VER)-config debian/python3-dev/usr/bin/python3-config ln -sf python$(VER)-config.1.gz \ debian/python3-dev/usr/share/man/man1/python3-config.1.gz : # provide pkgconfig defaults mkdir -p debian/python3-dev/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig ln -sf python-$(VER).pc debian/python3-dev/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python3.pc mkdir -p debian/python3-dbg/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig ln -sf python-$(VER)-dbg.pc debian/python3-dbg/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python3-dbg.pc ifeq (0,1) : # provide pyconfig.h in the non-multiarch location. mkdir -p debian/python3-dev/usr/include/python$(VER)m ln -sf ../$(DEB_HOST_MULTIARCH)/python$(VER)m/pyconfig.h \ debian/python3-dev/usr/include/python$(VER)m/pyconfig.h mkdir -p debian/python3-dbg/usr/include/python$(VER)dm ln -sf ../$(DEB_HOST_MULTIARCH)/python$(VER)dm/pyconfig.h \ debian/python3-dbg/usr/include/python$(VER)dm/pyconfig.h endif : # provide the python-dbg and python-dbg.1 defaults mkdir -p debian/python3-dbg/usr/bin ln -sf python$(VER)dm debian/python3-dbg/usr/bin/python3dm ln -sf python$(VER)dm-config debian/python3-dbg/usr/bin/python3dm-config ln -sf python$(VER)-dbg debian/python3-dbg/usr/bin/python3-dbg ln -sf python$(VER)-dbg-config debian/python3-dbg/usr/bin/python3-dbg-config mkdir -p debian/python3-dbg/usr/share/man/man1 ln -sf python$(VER)dm.1.gz \ debian/python3-dbg/usr/share/man/man1/python3dm.1.gz ln -sf python$(VER)dm-config.1.gz \ debian/python3-dbg/usr/share/man/man1/python3dm-config.1.gz ln -sf python$(VER)-dbg.1.gz \ debian/python3-dbg/usr/share/man/man1/python3-dbg.1.gz ln -sf python$(VER)-dbg-config.1.gz \ debian/python3-dbg/usr/share/man/man1/python3-dbg-config.1.gz mkdir -p debian/python3-dbg/usr/share/doc/python3 ln -sf ../python$(VER)/SpecialBuilds.txt.gz \ debian/python3-dbg/usr/share/doc/python3/SpecialBuilds.txt.gz ln -sf ../python$(VER)/README.debug \ debian/python3-dbg/usr/share/doc/python3/README.debug mkdir -p debian/python3/usr/lib/valgrind cp -p debian/valgrind-python.supp \ debian/python3/usr/lib/valgrind/python3.supp : # provide the DEB_HOST_GNU_TYPE/DEB_HOST_MULTIRACH python-config defaults mkdir -p debian/libpython3-dev/usr/bin ln -sf $(DEB_HOST_MULTIARCH)-python$(VER)m-config \ debian/libpython3-dev/usr/bin/$(DEB_HOST_MULTIARCH)-python3m-config ln -sf $(DEB_HOST_MULTIARCH)-python$(VER)-config \ debian/libpython3-dev/usr/bin/$(DEB_HOST_MULTIARCH)-python3-config mkdir -p debian/libpython3-dev/usr/share/man/man1 ln -sf $(DEB_HOST_MULTIARCH)-python$(VER)m-config.1.gz \ debian/libpython3-dev/usr/share/man/man1/$(DEB_HOST_MULTIARCH)-python3m-config.1.gz ln -sf $(DEB_HOST_MULTIARCH)-python$(VER)-config.1.gz \ debian/libpython3-dev/usr/share/man/man1/$(DEB_HOST_MULTIARCH)-python3-config.1.gz ifneq ($(DEB_HOST_MULTIARCH),$(DEB_HOST_GNU_TYPE)) ln -sf $(DEB_HOST_GNU_TYPE)-python$(VER)m-config \ debian/libpython3-dev/usr/bin/$(DEB_HOST_GNU_TYPE)-python3m-config ln -sf $(DEB_HOST_GNU_TYPE)-python$(VER)-config \ debian/libpython3-dev/usr/bin/$(DEB_HOST_GNU_TYPE)-python3-config ln -sf $(DEB_HOST_GNU_TYPE)-python$(VER)m-config.1.gz \ debian/libpython3-dev/usr/share/man/man1/$(DEB_HOST_GNU_TYPE)-python3m-config.1.gz ln -sf $(DEB_HOST_GNU_TYPE)-python$(VER)-config.1.gz \ debian/libpython3-dev/usr/share/man/man1/$(DEB_HOST_GNU_TYPE)-python3-config.1.gz endif mkdir -p debian/libpython3-dbg/usr/bin ln -sf $(DEB_HOST_MULTIARCH)-python$(VER)dm-config \ debian/libpython3-dbg/usr/bin/$(DEB_HOST_MULTIARCH)-python3dm-config ln -sf $(DEB_HOST_MULTIARCH)-python$(VER)-dbg-config \ debian/libpython3-dbg/usr/bin/$(DEB_HOST_MULTIARCH)-python3-dbg-config mkdir -p debian/libpython3-dbg/usr/share/man/man1 ln -sf $(DEB_HOST_MULTIARCH)-python$(VER)dm-config.1.gz \ debian/libpython3-dbg/usr/share/man/man1/$(DEB_HOST_MULTIARCH)-python3dm-config.1.gz ln -sf $(DEB_HOST_MULTIARCH)-python$(VER)-dbg-config.1.gz \ debian/libpython3-dbg/usr/share/man/man1/$(DEB_HOST_MULTIARCH)-python3-dbg-config.1.gz ifneq ($(DEB_HOST_MULTIARCH),$(DEB_HOST_GNU_TYPE)) ln -sf $(DEB_HOST_GNU_TYPE)-python$(VER)dm-config \ debian/libpython3-dbg/usr/bin/$(DEB_HOST_GNU_TYPE)-python3dm-config ln -sf $(DEB_HOST_GNU_TYPE)-python$(VER)-dbg-config \ debian/libpython3-dbg/usr/bin/$(DEB_HOST_GNU_TYPE)-python3-dbg-config ln -sf $(DEB_HOST_GNU_TYPE)-python$(VER)dm-config.1.gz \ debian/libpython3-dbg/usr/share/man/man1/$(DEB_HOST_GNU_TYPE)-python3dm-config.1.gz ln -sf $(DEB_HOST_GNU_TYPE)-python$(VER)-dbg-config.1.gz \ debian/libpython3-dbg/usr/share/man/man1/$(DEB_HOST_GNU_TYPE)-python3-dbg-config.1.gz endif : # provide the pyvenv and pyvenv.1 defaults mkdir -p debian/python3-venv/usr/bin ln -sf pyvenv-$(VER) debian/python3-venv/usr/bin/pyvenv mkdir -p debian/python3-venv/usr/share/man/man1 ln -sf pyvenv-$(VER).1.gz \ debian/python3-venv/usr/share/man/man1/pyvenv.1.gz dh_lintian -a dh_installdocs -a $(NOPKGS) --all debian/README.Debian dh_installchangelogs -a $(NOPKGS) for p in all all-dev all-dbg dbg dev venv; do \ case $$p in idle*) : ;; *) p=python3-$$p; esac; \ rm -rf debian/$$p/usr/share/doc/$$p; \ ln -sf python3 debian/$$p/usr/share/doc/$$p; \ done rm -rf debian/libpython3-all-dev/usr/share/doc/libpython3-all-dev ln -sf libpython3-dev debian/libpython3-all-dev/usr/share/doc/libpython3-all-dev rm -rf debian/libpython3-all-dbg/usr/share/doc/libpython3-all-dbg ln -sf libpython3-dbg debian/libpython3-all-dbg/usr/share/doc/libpython3-all-dbg dh_compress -a $(NOPKGS) dh_fixperms -a $(NOPKGS) dh_installdeb -a $(NOPKGS) dh_gencontrol -a $(NOPKGS) dh_md5sums -a $(NOPKGS) dh_builddeb -a $(NOPKGS) binary: binary-indep binary-arch .PHONY: control-file configure build clean binary-indep binary-arch binary install # Local Variables: # mode: makefile # end: python3-defaults-3.6.7/debian/source/0000775000000000000000000000000013305601050014343 5ustar python3-defaults-3.6.7/debian/source/format0000664000000000000000000000000413305601050015550 0ustar 1.0 python3-defaults-3.6.7/debian/source.lintian-overrides0000664000000000000000000000043213305601050017722 0ustar # this source package provides these packages so it cannot depend on them dbg-package-missing-depends python3-all-dbg dbg-package-missing-depends python3-dbg dbg-package-missing-depends libpython3-all-dbg dbg-package-missing-depends libpython3-dbg native-package-with-dash-version python3-defaults-3.6.7/debian/valgrind-python.supp0000664000000000000000000002134713305601050017110 0ustar # # This is a valgrind suppression file that should be used when using valgrind. # # --------------------------------------------------------------------------- # Debian note: # The file Misc/valgrind-python.supp is placed in an modified form into the # directory /usr/lib/valgrind as python.supp. There's no need to to add it # with the --suppressions option. # The unmodified file is found in /usr/share/doc/python3.6/ # # The python3.6-dbg build has been compiled with -DPy_USING_MEMORY_DEBUGGER # so you can safely comment out the suppressions for PyObject_Free and # PyObject_Realloc. # --------------------------------------------------------------------------- # Here's an example of running valgrind: # # cd python/dist/src # valgrind --tool=memcheck --suppressions=Misc/valgrind-python.supp \ # ./python -E ./Lib/test/regrtest.py -u gui,network # # You must edit Objects/obmalloc.c and uncomment Py_USING_MEMORY_DEBUGGER # to use the preferred suppressions with address_in_range. # # If you do not want to recompile Python, you can uncomment # suppressions for PyObject_Free and PyObject_Realloc. # # See Misc/README.valgrind for more information. # all tool names: Addrcheck,Memcheck,cachegrind,helgrind,massif { ADDRESS_IN_RANGE/Invalid read of size 4 Memcheck:Addr4 fun:address_in_range } { ADDRESS_IN_RANGE/Invalid read of size 4 Memcheck:Value4 fun:address_in_range } { ADDRESS_IN_RANGE/Invalid read of size 8 (x86_64 aka amd64) Memcheck:Value8 fun:address_in_range } { ADDRESS_IN_RANGE/Conditional jump or move depends on uninitialised value Memcheck:Cond fun:address_in_range } # # Leaks (including possible leaks) # Hmmm, I wonder if this masks some real leaks. I think it does. # Will need to fix that. # { Suppress leaking the GIL. Happens once per process, see comment in ceval.c. Memcheck:Leak fun:malloc fun:PyThread_allocate_lock fun:PyEval_InitThreads } { Suppress leaking the GIL after a fork. Memcheck:Leak fun:malloc fun:PyThread_allocate_lock fun:PyEval_ReInitThreads } { Suppress leaking the autoTLSkey. This looks like it shouldn't leak though. Memcheck:Leak fun:malloc fun:PyThread_create_key fun:_PyGILState_Init fun:Py_InitializeEx fun:Py_Main } { Hmmm, is this a real leak or like the GIL? Memcheck:Leak fun:malloc fun:PyThread_ReInitTLS } { Handle PyMalloc confusing valgrind (possibly leaked) Memcheck:Leak fun:realloc fun:_PyObject_GC_Resize fun:COMMENT_THIS_LINE_TO_DISABLE_LEAK_WARNING } { Handle PyMalloc confusing valgrind (possibly leaked) Memcheck:Leak fun:malloc fun:_PyObject_GC_New fun:COMMENT_THIS_LINE_TO_DISABLE_LEAK_WARNING } { Handle PyMalloc confusing valgrind (possibly leaked) Memcheck:Leak fun:malloc fun:_PyObject_GC_NewVar fun:COMMENT_THIS_LINE_TO_DISABLE_LEAK_WARNING } # # Non-python specific leaks # { Handle pthread issue (possibly leaked) Memcheck:Leak fun:calloc fun:allocate_dtv fun:_dl_allocate_tls_storage fun:_dl_allocate_tls } { Handle pthread issue (possibly leaked) Memcheck:Leak fun:memalign fun:_dl_allocate_tls_storage fun:_dl_allocate_tls } ###{ ### ADDRESS_IN_RANGE/Invalid read of size 4 ### Memcheck:Addr4 ### fun:PyObject_Free ###} ### ###{ ### ADDRESS_IN_RANGE/Invalid read of size 4 ### Memcheck:Value4 ### fun:PyObject_Free ###} ### ###{ ### ADDRESS_IN_RANGE/Use of uninitialised value of size 8 ### Memcheck:Addr8 ### fun:PyObject_Free ###} ### ###{ ### ADDRESS_IN_RANGE/Use of uninitialised value of size 8 ### Memcheck:Value8 ### fun:PyObject_Free ###} ### ###{ ### ADDRESS_IN_RANGE/Conditional jump or move depends on uninitialised value ### Memcheck:Cond ### fun:PyObject_Free ###} ###{ ### ADDRESS_IN_RANGE/Invalid read of size 4 ### Memcheck:Addr4 ### fun:PyObject_Realloc ###} ### ###{ ### ADDRESS_IN_RANGE/Invalid read of size 4 ### Memcheck:Value4 ### fun:PyObject_Realloc ###} ### ###{ ### ADDRESS_IN_RANGE/Use of uninitialised value of size 8 ### Memcheck:Addr8 ### fun:PyObject_Realloc ###} ### ###{ ### ADDRESS_IN_RANGE/Use of uninitialised value of size 8 ### Memcheck:Value8 ### fun:PyObject_Realloc ###} ### ###{ ### ADDRESS_IN_RANGE/Conditional jump or move depends on uninitialised value ### Memcheck:Cond ### fun:PyObject_Realloc ###} ### ### All the suppressions below are for errors that occur within libraries ### that Python uses. The problems to not appear to be related to Python's ### use of the libraries. ### { Generic ubuntu ld problems Memcheck:Addr8 obj:/lib/ld-2.4.so obj:/lib/ld-2.4.so obj:/lib/ld-2.4.so obj:/lib/ld-2.4.so } { Generic gentoo ld problems Memcheck:Cond obj:/lib/ld-2.3.4.so obj:/lib/ld-2.3.4.so obj:/lib/ld-2.3.4.so obj:/lib/ld-2.3.4.so } { DBM problems, see test_dbm Memcheck:Param write(buf) fun:write obj:/usr/lib/libdb1.so.2 obj:/usr/lib/libdb1.so.2 obj:/usr/lib/libdb1.so.2 obj:/usr/lib/libdb1.so.2 fun:dbm_close } { DBM problems, see test_dbm Memcheck:Value8 fun:memmove obj:/usr/lib/libdb1.so.2 obj:/usr/lib/libdb1.so.2 obj:/usr/lib/libdb1.so.2 obj:/usr/lib/libdb1.so.2 fun:dbm_store fun:dbm_ass_sub } { DBM problems, see test_dbm Memcheck:Cond obj:/usr/lib/libdb1.so.2 obj:/usr/lib/libdb1.so.2 obj:/usr/lib/libdb1.so.2 fun:dbm_store fun:dbm_ass_sub } { DBM problems, see test_dbm Memcheck:Cond fun:memmove obj:/usr/lib/libdb1.so.2 obj:/usr/lib/libdb1.so.2 obj:/usr/lib/libdb1.so.2 obj:/usr/lib/libdb1.so.2 fun:dbm_store fun:dbm_ass_sub } { GDBM problems, see test_gdbm Memcheck:Param write(buf) fun:write fun:gdbm_open } { ZLIB problems, see test_gzip Memcheck:Cond obj:/lib/libz.so.1.2.3 obj:/lib/libz.so.1.2.3 fun:deflate } { Avoid problems w/readline doing a putenv and leaking on exit Memcheck:Leak fun:malloc fun:xmalloc fun:sh_set_lines_and_columns fun:_rl_get_screen_size fun:_rl_init_terminal_io obj:/lib/libreadline.so.4.3 fun:rl_initialize } ### ### These occur from somewhere within the SSL, when running ### test_socket_sll. They are too general to leave on by default. ### ###{ ### somewhere in SSL stuff ### Memcheck:Cond ### fun:memset ###} ###{ ### somewhere in SSL stuff ### Memcheck:Value4 ### fun:memset ###} ### ###{ ### somewhere in SSL stuff ### Memcheck:Cond ### fun:MD5_Update ###} ### ###{ ### somewhere in SSL stuff ### Memcheck:Value4 ### fun:MD5_Update ###} # Fedora's package "openssl-1.0.1-0.1.beta2.fc17.x86_64" on x86_64 # See http://bugs.python.org/issue14171 { openssl 1.0.1 prng 1 Memcheck:Cond fun:bcmp fun:fips_get_entropy fun:FIPS_drbg_instantiate fun:RAND_init_fips fun:OPENSSL_init_library fun:SSL_library_init fun:init_hashlib } { openssl 1.0.1 prng 2 Memcheck:Cond fun:fips_get_entropy fun:FIPS_drbg_instantiate fun:RAND_init_fips fun:OPENSSL_init_library fun:SSL_library_init fun:init_hashlib } { openssl 1.0.1 prng 3 Memcheck:Value8 fun:_x86_64_AES_encrypt_compact fun:AES_encrypt } # # All of these problems come from using test_socket_ssl # { from test_socket_ssl Memcheck:Cond fun:BN_bin2bn } { from test_socket_ssl Memcheck:Cond fun:BN_num_bits_word } { from test_socket_ssl Memcheck:Value4 fun:BN_num_bits_word } { from test_socket_ssl Memcheck:Cond fun:BN_mod_exp_mont_word } { from test_socket_ssl Memcheck:Cond fun:BN_mod_exp_mont } { from test_socket_ssl Memcheck:Param write(buf) fun:write obj:/usr/lib/libcrypto.so.0.9.7 } { from test_socket_ssl Memcheck:Cond fun:RSA_verify } { from test_socket_ssl Memcheck:Value4 fun:RSA_verify } { from test_socket_ssl Memcheck:Value4 fun:DES_set_key_unchecked } { from test_socket_ssl Memcheck:Value4 fun:DES_encrypt2 } { from test_socket_ssl Memcheck:Cond obj:/usr/lib/libssl.so.0.9.7 } { from test_socket_ssl Memcheck:Value4 obj:/usr/lib/libssl.so.0.9.7 } { from test_socket_ssl Memcheck:Cond fun:BUF_MEM_grow_clean } { from test_socket_ssl Memcheck:Cond fun:memcpy fun:ssl3_read_bytes } { from test_socket_ssl Memcheck:Cond fun:SHA1_Update } { from test_socket_ssl Memcheck:Value4 fun:SHA1_Update } { test_buffer_non_debug Memcheck:Addr4 fun:PyUnicodeUCS2_FSConverter } { test_buffer_non_debug Memcheck:Addr4 fun:PyUnicode_FSConverter } { wcscmp_false_positive Memcheck:Addr8 fun:wcscmp fun:_PyOS_GetOpt fun:Py_Main fun:main } # Additional suppressions for the unified decimal tests: { test_decimal Memcheck:Addr4 fun:PyUnicodeUCS2_FSConverter } { test_decimal2 Memcheck:Addr4 fun:PyUnicode_FSConverter } python3-defaults-3.6.7/debian/watch0000664000000000000000000000012013305601050014065 0ustar version=4 https://www.python.org/downloads/ .*/Python@ANY_VERSION@@ARCHIVE_EXT@ python3-defaults-3.6.7/debpython/0000775000000000000000000000000013305601050013615 5ustar python3-defaults-3.6.7/debpython/__init__.py0000664000000000000000000000352513305601050015733 0ustar try: from datetime import datetime except ImportError: datetime = None import logging import re from subprocess import PIPE, Popen from pickle import dumps log = logging.getLogger(__name__) PUBLIC_DIR_RE = re.compile(r'.*?/usr/lib/python(\d(?:.\d+)?)/(site|dist)-packages') class memoize: def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args, **kwargs): key = dumps((args, kwargs)) if key not in self.cache: self.cache[key] = self.func(*args, **kwargs) return self.cache[key] def execute(command, cwd=None, env=None, log_output=None): """Execute external shell commad. :param cdw: currennt working directory :param env: environment :param log_output: * opened log file or path to this file, or * None if output should be included in the returned dict, or * False if output should be redirectored to stdout/stderr """ args = {'shell': True, 'cwd': cwd, 'env': env} close = False if log_output is False: pass elif log_output is None: args.update(stdout=PIPE, stderr=PIPE) elif log_output: if isinstance(log_output, str): close = True log_output = open(log_output, 'a') if datetime: log_output.write('\n# command executed on {}'.format(datetime.now().isoformat())) log_output.write('\n$ {}\n'.format(command)) log_output.flush() args.update(stdout=log_output, stderr=log_output) log.debug('invoking: %s', command) with Popen(command, **args) as process: stdout, stderr = process.communicate() close and log_output.close() return dict(returncode=process.returncode, stdout=stdout and str(stdout, 'utf-8'), stderr=stderr and str(stderr, 'utf-8')) python3-defaults-3.6.7/debpython/files.py0000664000000000000000000000631613305601050015277 0ustar # Copyright © 2012 Piotr Ożarowski # # 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. import logging from os import walk from os.path import abspath, isfile, join from subprocess import Popen, PIPE from debpython import PUBLIC_DIR_RE log = logging.getLogger(__name__) def from_directory(dname, extensions=('.py',)): """Generate *.py file names available in given directory.""" extensions = tuple(extensions) # .endswith doesn't like list if isinstance(dname, (list, tuple)): for item in dname: for fn in from_directory(item): yield fn elif isfile(dname) and dname.endswith(extensions): yield dname else: for root, dirs, file_names in walk(abspath(dname)): for fn in file_names: if fn.endswith(extensions): yield join(root, fn) def from_package(package_name, extensions=('.py',)): """Generate *.py file names available in given package.""" extensions = tuple(extensions) # .endswith doesn't like list process = Popen("/usr/bin/dpkg -L %s" % package_name, shell=True, stdout=PIPE) stdout, stderr = process.communicate() if process.returncode != 0: raise Exception("cannot get content of %s" % package_name) stdout = str(stdout, 'utf-8') for line in stdout.splitlines(): if line.endswith(extensions): yield line def filter_directory(files, dname): """Generate *.py file names that match given directory.""" for fn in files: if fn.startswith(dname): yield fn def filter_public(files, versions): """Generate *.py file names that match given versions.""" vstr = set("%d.%d" % i for i in versions) shared_vstr = set(str(i[0]) for i in versions) for fn in files: public_dir = PUBLIC_DIR_RE.match(fn) if public_dir: vers = public_dir.group(1) if vers in shared_vstr or vers in vstr: yield fn def filter_out_ext(files, extensions): """Removes files with matching extensions from given generator.""" extensions = tuple(extensions) # .endswith doesn't like list for fn in files: if not fn.endswith(extensions): yield fn python3-defaults-3.6.7/debpython/interpreter.py0000664000000000000000000003230713305601050016537 0ustar # Copyright © 2012 Piotr Ożarowski # # 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. import logging import os import re from os.path import join, split from debpython import execute from debpython.version import Version SHEBANG_RE = re.compile(r''' (?:\#!\s*){0,1} # shebang prefix (?P .*?/bin/.*?)? (?P python|pypy) (?P \d[\.\d]*)? (?P -dbg)? (?P.*) ''', re.VERBOSE) EXTFILE_RE = re.compile(r''' (?P.*?) (?:\. (?Pabi\d+) |(?:\. (?P (?Pcpython|pypy) - (?P\d{2}) (?P[a-z]*?) ) (?: -(?P[^/]*?) )? ))? (?P_d)? \.so$''', re.VERBOSE) log = logging.getLogger(__name__) class Interpreter: path = None name = 'python' version = None debug = False impl = 'cpython' # implementation options = () _cache = {} def __init__(self, value=None, path=None, name=None, version=None, debug=None, impl=None, options=None): params = locals() del params['self'] del params['value'] if isinstance(value, Interpreter): for key in params.keys(): if params[key] is None: params[key] = getattr(value, key) elif value: if value.replace('.', '').isdigit() and not version: params['version'] = Version(value) else: for key, val in self.parse(value).items(): if params[key] is None: params[key] = val for key, val in params.items(): setattr(self, key, val) def __setattr__(self, name, value): if name == 'name' and value: if value.startswith('python'): self.__dict__['impl'] = 'cpython' elif value.startswith('pypy'): self.__dict__['impl'] = 'pypy' if '-dbg' in value: self.__dict__['debug'] = True elif name == 'version' and value is not None: value = Version(value) if name in ('name', 'impl', 'debug', 'options') and value is None: # get the class default instead self.__dict__[name] = getattr(Interpreter, name) else: self.__dict__[name] = value def __repr__(self): result = self.path or '' result += self._vstr(self.version) if self.options: result += ' ' + ' '.join(self.options) return result def __str__(self): return self._vstr(self.version) def _vstr(self, version): if self.impl == 'pypy': # TODO: will Debian support more than one PyPy version? return self.name if version and str(version) not in self.name: if self.debug: return 'python{}-dbg'.format(version) return self.name + str(version) return self.name @staticmethod def parse(shebang): """Return dict with parsed shebang >>> sorted(Interpreter.parse('pypy').items()) [('debug', None), ('name', 'pypy'), ('options', ()), ('path', None), ('version', None)] >>> sorted(Interpreter.parse('/usr/bin/python3.3-dbg').items()) [('debug', '-dbg'), ('name', 'python'), ('options', ()), ('path', '/usr/bin/'), ('version', '3.3')] >>> sorted(Interpreter.parse('#! /usr/bin/pypy --foo').items()) [('debug', None), ('name', 'pypy'), ('options', ('--foo',)), ('path', '/usr/bin/'), ('version', None)] >>> sorted(Interpreter.parse('#! /usr/bin/python3.2').items()) [('debug', None), ('name', 'python'), ('options', ()), ('path', '/usr/bin/'), ('version', '3.2')] >>> sorted(Interpreter.parse('/usr/bin/python3.2-dbg --foo --bar').items()) [('debug', '-dbg'), ('name', 'python'), ('options', ('--foo', '--bar')),\ ('path', '/usr/bin/'), ('version', '3.2')] """ result = SHEBANG_RE.search(shebang) if not result: return {} result = result.groupdict() if 'options' in result: # TODO: do we need "--key value" here? result['options'] = tuple(result['options'].split()) return result def sitedir(self, gdb=False, package=None, version=None): """Return path to site-packages directory. Note that returned path is not the final location of .py files >>> i = Interpreter('python') >>> i.sitedir(version='3.1') '/usr/lib/python3/dist-packages/' >>> i.sitedir(version='2.5') '/usr/lib/python2.5/site-packages/' >>> i.sitedir(version=Version('2.7')) '/usr/lib/python2.7/dist-packages/' >>> i.sitedir(version='3.1', gdb=True, package='python3-foo') 'debian/python3-foo/usr/lib/debug/usr/lib/python3/dist-packages/' >>> i.sitedir(version=Version('3.2')) '/usr/lib/python3/dist-packages/' >>> Interpreter('pypy').sitedir(version='2.0') '/usr/lib/pypy/dist-packages/' """ version = Version(version or self.version) #if not version: # version = Version(DEFAULT) if self.impl == 'pypy': path = '/usr/lib/pypy/dist-packages/' elif version << Version('2.6'): path = "/usr/lib/python%s/site-packages/" % version elif version << Version('3.0'): path = "/usr/lib/python%s/dist-packages/" % version else: path = '/usr/lib/python3/dist-packages/' if gdb: path = "/usr/lib/debug%s" % path if package: path = "debian/%s%s" % (package, path) return path def cache_file(self, fpath, version=None): """Given path to a .py file, return path to its .pyc/.pyo file. This function is inspired by Python 3.2's imp.cache_from_source. :param fpath: path to file name :param version: Python version >>> i = Interpreter('python') >>> i.cache_file('foo.py', Version('3.1')) 'foo.pyc' >>> i.cache_file('bar/foo.py', '3.2') 'bar/__pycache__/foo.cpython-32.pyc' """ version = Version(version or self.version) last_char = 'o' if '-O' in self.options else 'c' if version <= Version('3.1'): return fpath + last_char fdir, fname = split(fpath) if not fname.endswith('.py'): fname += '.py' return join(fdir, '__pycache__', "%s.%s.py%s" % (fname[:-3], self.magic_tag(version), last_char)) def ext_file(self, name, version=None): """Return extension name with soname and multiarch tags.""" version = Version(version or self.version) soabi, multiarch = self._get_config(version) result = name.split('.', 1)[0] if soabi: result += '.{}'.format(soabi) if multiarch: result += '-{}'.format(multiarch) if self.debug and self.impl == 'cpython'\ and version << Version('3'): result += '_d' return '{}.so'.format(result) def magic_number(self, version=None): """Return magic number.""" version = Version(version or self.version) if self.impl == 'cpython' and version << Version('3'): return '' result = self._execute('import imp; print(imp.get_magic())', version) return eval(result) def magic_tag(self, version=None): """Return Python magic tag (used in __pycache__ dir to tag files). >>> i = Interpreter('python') >>> i.magic_tag(version='3.2') 'cpython-32' """ version = Version(version or self.version) if self.impl == 'cpython' and version << Version('3.2'): return '' return self._execute('import imp; print(imp.get_tag())', version) def multiarch(self, version=None): """Return multiarch tag.""" version = Version(version or self.version) try: soabi, multiarch = self._get_config(version) except Exception: log.debug('cannot get multiarch', exc_info=True) # interpreter without multiach support return '' return multiarch def stableabi(self, version=None): version = Version(version or self.version) # stable ABI was introduced in Python 3.3 if self.impl == 'cpython' and version >> Version('3.2'): return 'abi{}'.format(version.major) def soabi(self, version=None): """Return SOABI flag (used to in .so files). >>> i = Interpreter('python') >>> i.soabi(version=Version('3.3')) 'cpython-33m' """ version = Version(version or self.version) # NOTE: it's not the same as magic_tag try: soabi, multiarch = self._get_config(version) except Exception: log.debug('cannot get soabi', exc_info=True) # interpreter without soabi support return '' return soabi def check_extname(self, fname, version=None): """Return extension file name if file can be renamed. >>> i = Interpreter('python') >>> i.check_extname('foo.so', version='3.3') # doctest: +ELLIPSIS 'foo.cpython-33m-....so' >>> i.check_extname('foo.abi3.so', version='3.3') >>> i.check_extname('foo/bar/bazmodule.so', version='3.3') # doctest: +ELLIPSIS 'foo/bar/baz.cpython-33m-....so' """ version = Version(version or self.version) if '/' in fname: fdir, fname = fname.rsplit('/', 1) # in case full path was passed else: fdir = '' info = EXTFILE_RE.search(fname) if not info: return info = info.groupdict() if info['stableabi']: # files with stable ABI in name don't need changes return i = Interpreter(self, version=version) if info['ver']: i.version = "{}.{}".format(info['ver'][0], info['ver'][1]) if not i.debug and (info['debug'] or 'd' in (info['flags'] or '')): i.debug = True try: soabi, multiarch = i._get_config() except Exception: log.debug('cannot get soabi/multiarch', exc_info=True) return result = info['name'] if i.impl == 'cpython' and i.version >> '3.2' and result.endswith('module'): result = result[:-6] if info['soabi'] or soabi: result = "{}.{}".format(result, info['soabi'] or soabi) if info['multiarch'] or multiarch: result = "{}-{}".format(result, info['multiarch'] or multiarch) result += '.so' if fname == result: return return join(fdir, result) def _get_config(self, version=None): version = Version(version or self.version) # sysconfig module is available since Python 3.2 # (also backported to Python 2.7) if self.impl == 'pypy' or self.impl == 'cpython' and ( version >> '2.6' and version << '3' or version >> '3.1' or version == '3'): cmd = 'import sysconfig as s;' else: cmd = 'from distutils import sysconfig as s;' cmd += 'print("__SEP__".join(i or "" ' \ 'for i in s.get_config_vars("SOABI", "MULTIARCH")))' conf_vars = self._execute(cmd, version).split('__SEP__') try: conf_vars[1] = os.environ['DEB_HOST_MULTIARCH'] except KeyError: pass return conf_vars def _execute(self, command, version=None, cache=True): version = Version(version or self.version) command = "{} -c '{}'".format(self._vstr(version), command.replace("'", "\'")) if cache and command in self.__class__._cache: return self.__class__._cache[command] output = execute(command) if output['returncode'] != 0: log.debug(output['stderr']) raise Exception('{} failed with status code {}'.format(command, output['returncode'])) result = output['stdout'].splitlines() if len(result) == 1: result = result[0] if cache: self.__class__._cache[command] = result return result python3-defaults-3.6.7/debpython/option.py0000664000000000000000000000353613305601050015506 0ustar # -*- coding: UTF-8 -*- # Copyright © 2010-2012 Piotr Ożarowski # # 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. import re import optparse from copy import copy from debpython.version import parse_vrange def parse_version_range(option, opt, value): try: return parse_vrange(value) except ValueError: raise optparse.OptionValueError("version range is invalid: %s" % value) def compile_regexpr(option, opt, value): try: pattern = re.compile(value) except Exception: raise optparse.OptionValueError('regular expression is not valid') return pattern class Option(optparse.Option): TYPES = optparse.Option.TYPES + ('version_range', 'regexpr') TYPE_CHECKER = copy(optparse.Option.TYPE_CHECKER) TYPE_CHECKER['version_range'] = parse_version_range TYPE_CHECKER['regexpr'] = compile_regexpr python3-defaults-3.6.7/debpython/version.py0000664000000000000000000003366113305601050015665 0ustar # -*- coding: UTF-8 -*- # Copyright © 2010-2012 Piotr Ożarowski # # 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. import logging import re from os import environ from os.path import exists from configparser import ConfigParser from types import GeneratorType RANGE_PATTERN = r'(-)?(\d\.\d+)(?:(-)(\d\.\d+)?)?' RANGE_RE = re.compile(RANGE_PATTERN) VERSION_RE = re.compile(r''' (?P\d+)\.? (?P\d+)?\.? (?P\d+)?[.\s]? (?Palpha|beta|candidate|final)?[.\s]? (?P\d+)?''', re.VERBOSE) log = logging.getLogger(__name__) # try to read debian_defaults and get a list of supported Python versions and # the default one from there _supported = environ.get('DEBPYTHON3_SUPPORTED') _default = environ.get('DEBPYTHON3_DEFAULT') if not _supported or not _default: _config = ConfigParser() _config.read('/usr/share/python3/debian_defaults') if not _default: _default = _config.get('DEFAULT', 'default-version')[6:] if not _supported: _supported = _config.get('DEFAULT', 'supported-versions')\ .replace('python', '') try: DEFAULT = tuple(int(i) for i in _default.split('.')) except Exception: log.exception('cannot read debian_defaults') try: SUPPORTED = tuple(tuple(int(j) for j in i.strip().split('.')) for i in _supported.split(',')) except Exception: log.exception('cannot read debian_defaults') class Version: def __init__(self, value=None, major=None, minor=None, micro=None, releaselevel=None, serial=None): if isinstance(value, (tuple, list)): value = '.'.join(str(i) for i in value) if isinstance(value, Version): for name in ('major', 'minor', 'micro', 'releaselevel', 'serial'): setattr(self, name, getattr(value, name)) return comp = locals() del comp['self'] del comp['value'] if value: match = VERSION_RE.match(value) for name, value in match.groupdict().items() if match else []: if value is not None and comp[name] is None: comp[name] = value for name, value in comp.items(): if name != 'releaselevel' and value is not None: value = int(value) setattr(self, name, value) if not self.major: raise ValueError('major component is required') def __str__(self): """Return major.minor or major string. >>> str(Version(major=3, minor=2, micro=1, releaselevel='final', serial=4)) '3.2' >>> str(Version(major=2)) '2' """ result = str(self.major) if self.minor is not None: result += '.{}'.format(self.minor) return result def __hash__(self): return hash(repr(self)) def __repr__(self): """Return full version string. >>> repr(Version(major=3, minor=2, micro=1, releaselevel='final', serial=4)) "Version('3.2.1.final.4')" >>> repr(Version(major=2)) "Version('2')" """ result = "Version('{}".format(self) for name in ('micro', 'releaselevel', 'serial'): value = getattr(self, name) if not value: break result += '.{}'.format(value) return result + "')" def __add__(self, other): """Return next version. >>> Version('3.1') + 1 Version('3.2') >>> Version('2') + '1' Version('3') """ result = Version(self) if self.minor is None: result.major += int(other) else: result.minor += int(other) return result def __sub__(self, other): """Return previous version. >>> Version('3.1') - 1 Version('3.0') >>> Version('3') - '1' Version('2') """ result = Version(self) if self.minor is None: result.major -= int(other) new = result.major else: result.minor -= int(other) new = result.minor if new < 0: raise ValueError('cannot decrease version further') return result def __eq__(self, other): return self.__cmp(other) == 0 def __lt__(self, other): return self.__cmp(other) < 0 def __le__(self, other): return self.__cmp(other) <= 0 def __gt__(self, other): return self.__cmp(other) > 0 def __ge__(self, other): return self.__cmp(other) >= 0 def __lshift__(self, other): """Compare major.minor or major only (if minor is not set). >>> Version('2.6') << Version('2.7') True >>> Version('2.6') << Version('2.6.6') False >>> Version('3') << Version('2') False >>> Version('3.1') << Version('2') False >>> Version('2') << Version('3.2.1.alpha.3') True """ if not isinstance(other, Version): other = Version(other) if self.minor is None or other.minor is None: return self.__cmp(other, ignore='minor') < 0 else: return self.__cmp(other, ignore='micro') < 0 def __rshift__(self, other): """Compare major.minor or major only (if minor is not set). >>> Version('2.6') >> Version('2.7') False >>> Version('2.6.7') >> Version('2.6.6') False >>> Version('3') >> Version('2') True >>> Version('3.1') >> Version('2') True >>> Version('2.1') >> Version('3.2.1.alpha.3') False """ if not isinstance(other, Version): other = Version(other) if self.minor is None or other.minor is None: return self.__cmp(other, ignore='minor') > 0 else: return self.__cmp(other, ignore='micro') > 0 def __cmp(self, other, ignore=None): if not isinstance(other, Version): other = Version(other) for name in ('major', 'minor', 'micro', 'releaselevel', 'serial'): if name == ignore: break value1 = getattr(self, name) or 0 value2 = getattr(other, name) or 0 if name == 'releaselevel': rmap = {'alpha': -3, 'beta': -2, 'candidate': -1, 'final': 0} value1 = rmap.get(value1, 0) value2 = rmap.get(value2, 0) if value1 == value2: continue return (value1 > value2) - (value1 < value2) return 0 def get_requested_versions(vrange=None, available=None): """Return a set of requested and supported Python versions. :param available: if set to `True`, return installed versions only, if set to `False`, return requested versions that are not installed. By default returns all requested versions. :type available: bool >>> sorted(get_requested_versions([(3, 0), None])) [(3, 2), (3, 3)] >>> sorted(get_requested_versions('')) == sorted(SUPPORTED) True >>> sorted(get_requested_versions([None, None])) == sorted(SUPPORTED) True >>> get_requested_versions([(5, 0), None]) == set() True """ if isinstance(vrange, str): vrange = parse_vrange(vrange) if not vrange or list(vrange) == [None, None]: versions = set(SUPPORTED) else: minv = (0, 0) if vrange[0] is None else vrange[0] maxv = (99, 99) if vrange[1] is None else vrange[1] if minv == maxv: versions = set((minv,) if minv in SUPPORTED else tuple()) else: versions = set(v for v in SUPPORTED if minv <= v < maxv) if available: versions = set(v for v in versions if exists("/usr/bin/python%d.%d" % v)) elif available is False: versions = set(v for v in versions if not exists("/usr/bin/python%d.%d" % v)) return versions def parse_vrange(value): """Return minimum and maximum Python version from given range. >>> parse_vrange('3.0-') ((3, 0), None) >>> parse_vrange('3.1-3.3') ((3, 1), (3, 3)) >>> parse_vrange('3.2-4.0') ((3, 2), (4, 0)) >>> parse_vrange('-3.7') (None, (3, 7)) >>> parse_vrange('3.2') ((3, 2), (3, 2)) >>> parse_vrange('') == parse_vrange('-') == (None, None) True """ if value in ('', '-'): return None, None match = RANGE_RE.match(value) if not match: raise ValueError("version range is invalid: %s" % value) groups = match.groups() if list(groups).count(None) == 3: # only one version is allowed minv = tuple(int(i) for i in groups[1].split('.')) return minv, minv minv = maxv = None if groups[0]: # maximum version only maxv = groups[1] else: minv = groups[1] maxv = groups[3] minv = tuple(int(i) for i in minv.split('.')) if minv else None maxv = tuple(int(i) for i in maxv.split('.')) if maxv else None if maxv and minv and minv > maxv: raise ValueError("version range is invalid: %s" % value) return minv, maxv def parse_pycentral_vrange(value): """Parse X-Python3-Version. >>> parse_pycentral_vrange('>= 3.1') ((3, 1), None) >>> parse_pycentral_vrange('<< 4.0') (None, (4, 0)) >>> parse_pycentral_vrange('3.1') ((3, 1), (3, 1)) >>> parse_pycentral_vrange('3.1, 3.2') ((3, 1), None) """ #get = lambda x: get_requested_versions(parse_vrange(x)) minv = maxv = None hardcoded = set() for item in value.split(','): item = item.strip() match = re.match(r'>=\s*([\d\.]+)', item) if match: minv = "%.3s" % match.group(1) continue match = re.match(r'<<\s*([\d\.]+)', item) if match: maxv = "%.3s" % match.group(1) continue match = re.match(r'^[\d\.]+$', item) if match: hardcoded.add("%.3s" % match.group(0)) if len(hardcoded) == 1: ver = hardcoded.pop() return getver(ver), getver(ver) if not minv and hardcoded: # yeah, no maxv! minv = sorted(hardcoded)[0] return getver(minv) if minv else None, getver(maxv) if maxv else None def vrange_str(vrange): """Return version range string from given range. >>> vrange_str(((3, 4), None)) '3.4-' >>> vrange_str(((3, 4), (3, 6))) '3.4-3.6' >>> vrange_str(((3, 4), (4, 0))) '3.4-4.0' >>> vrange_str((None, (3, 7))) '-3.7' >>> vrange_str(((3, 5), (3, 5))) '3.5' >>> vrange_str((None, None)) '-' """ if vrange[0] is vrange[1] is None: return '-' if vrange[0] == vrange[1]: return '.'.join(str(i) for i in vrange[0]) elif vrange[0] is None: return '-' + '.'.join(str(i) for i in vrange[1]) elif vrange[1] is None: return '.'.join(str(i) for i in vrange[0]) + '-' else: return "%s-%s" % ('.'.join(str(i) for i in vrange[0]), '.'.join(str(i) for i in vrange[1])) def vrepr(value): """ >>> vrepr(([3, 4], [3, 2])) ['3.4', '3.2'] >>> vrepr(('2.6', '3.1')) ['2.6', '3.1'] >>> vrepr('3.2') '3.2' >>> vrepr((3, 2)) '3.2' """ if isinstance(value, str): return value elif not isinstance(value, (GeneratorType, set)) and isinstance(value[0], int): return '.'.join(str(i) for i in value) result = [] for version in value: if isinstance(version, str): result.append(version) else: result.append('.'.join(str(i) for i in version)) return result def getver(value): """Return pair of integers that represent version. >>> getver('3.2') (3, 2) >>> getver('3.1.4') (3, 1) >>> getver((3, 3, 1)) (3, 3) >>> getver(None) '' """ if not value: return '' if isinstance(value, tuple): return value[:2] return tuple(int(i) for i in value.split('.', 2))[:2] def debsorted(versions, return_str=None): """Return sorted list of versions starting with default Python version (if available) then list of suppored versions greater than default one followed by reversed list of older versions. List of versions sorted this way can be used in Depends field. :param vrepr: return string represenatations of versions, by default the same format is used as in :param:`versions` >>> debsorted([(2, 6), (3, 1), (3, 2), (3, 3), (2, 7)])[0] == DEFAULT True >>> debsorted(('2.4', '3.2', '2.6', '2.7'))[-1] (2, 4) >>> debsorted(set([(2, 1), (2, 2)])) [(2, 2), (2, 1)] >>> debsorted([(2, 1), (2, 2)], return_str=True) ['2.2', '2.1'] """ result = [] old_versions = [] for version in sorted(versions): if isinstance(version, str): version = getver(version) if version < DEFAULT: old_versions.append(version) else: result.append(version) result.extend(reversed(old_versions)) if return_str and result: return vrepr(result) return result python3-defaults-3.6.7/faq/0000775000000000000000000000000013305601050012370 5ustar python3-defaults-3.6.7/faq/FAQ.ht0000664000000000000000000000123113305601050013331 0ustar Title: Python Frequently Asked Question Lists Content-type: text/x-rst ========================================== Python Frequently Asked Question Lists ========================================== * `General Python FAQ `_ * `Programming FAQ `_ * `Library and Extension FAQ `_ * `Extending/Embedding FAQ `_ * `Windows FAQ `_ * `GUI Programming FAQ `_ * `"Why is Python Installed on my Computer?" FAQ `_ This is a local copy of the online FAQ located at http://python.org/doc/faq. The copy was fetched and generated in Februar 2007. python3-defaults-3.6.7/faq/extending.ht0000664000000000000000000004367213305601050014726 0ustar Title: Python Extending/Embedding FAQ Content-type: text/x-rst ==================================== Extending/Embedding FAQ ==================================== :Date: $Date: 2004-04-08 09:05:47 -0600 (Thu, 08 Apr 2004) $ :Version: $Revision: 7294 $ :Web site: http://www.python.org/ .. contents:: .. sectnum:: Can I create my own functions in C? ------------------------------------------ Yes, you can create built-in modules containing functions, variables, exceptions and even new types in C. This is explained in the document "Extending and Embedding the Python Interpreter" (http://docs.python.org/ext/ext.html). Most intermediate or advanced Python books will also cover this topic. Can I create my own functions in C++? -------------------------------------------- Yes, using the C compatibility features found in C++. Place ``extern "C" { ... }`` around the Python include files and put ``extern "C"`` before each function that is going to be called by the Python interpreter. Global or static C++ objects with constructors are probably not a good idea. Writing C is hard; are there any alternatives? --------------------------------------------------- There are a number of alternatives to writing your own C extensions, depending on what you're trying to do. If you need more speed, `Psyco `_ generates x86 assembly code from Python bytecode. You can use Psyco to compile the most time-critical functions in your code, and gain a significant improvement with very little effort, as long as you're running on a machine with an x86-compatible processor. `Pyrex `_ is a compiler that accepts a slightly modified form of Python and generates the corresponding C code. Pyrex makes it possible to write an extension without having to learn Python's C API. If you need to interface to some C library for which no Python extension currently exists, you can try wrapping the library's data types and functions with a tool such as `SWIG `_. For C++ libraries, you can look at `SIP `_, `CXX `_, `Boost `_, or `Weave `_. How can I execute arbitrary Python statements from C? ------------------------------------------------------------ The highest-level function to do this is ``PyRun_SimpleString()`` which takes a single string argument to be executed in the context of the module ``__main__`` and returns 0 for success and -1 when an exception occurred (including ``SyntaxError``). If you want more control, use ``PyRun_String()``; see the source for ``PyRun_SimpleString()`` in Python/pythonrun.c. How can I evaluate an arbitrary Python expression from C? ---------------------------------------------------------------- Call the function ``PyRun_String()`` from the previous question with the start symbol ``Py_eval_input``; it parses an expression, evaluates it and returns its value. How do I extract C values from a Python object? ------------------------------------------------------ That depends on the object's type. If it's a tuple, ``PyTupleSize(o)`` returns its length and ``PyTuple_GetItem(o, i)`` returns its i'th item. Lists have similar functions, ``PyListSize(o)`` and ``PyList_GetItem(o, i)``. For strings, ``PyString_Size(o)`` returns its length and ``PyString_AsString(o)`` a pointer to its value. Note that Python strings may contain null bytes so C's ``strlen()`` should not be used. To test the type of an object, first make sure it isn't NULL, and then use ``PyString_Check(o)``, ``PyTuple_Check(o)``, ``PyList_Check(o)``, etc. There is also a high-level API to Python objects which is provided by the so-called 'abstract' interface -- read ``Include/abstract.h`` for further details. It allows interfacing with any kind of Python sequence using calls like ``PySequence_Length()``, ``PySequence_GetItem()``, etc.) as well as many other useful protocols. How do I use Py_BuildValue() to create a tuple of arbitrary length? -------------------------------------------------------------------------- You can't. Use ``t = PyTuple_New(n)`` instead, and fill it with objects using ``PyTuple_SetItem(t, i, o)`` -- note that this "eats" a reference count of ``o``, so you have to ``Py_INCREF`` it. Lists have similar functions ``PyList_New(n)`` and ``PyList_SetItem(l, i, o)``. Note that you *must* set all the tuple items to some value before you pass the tuple to Python code -- ``PyTuple_New(n)`` initializes them to NULL, which isn't a valid Python value. How do I call an object's method from C? ----------------------------------------------- The ``PyObject_CallMethod()`` function can be used to call an arbitrary method of an object. The parameters are the object, the name of the method to call, a format string like that used with ``Py_BuildValue()``, and the argument values:: PyObject * PyObject_CallMethod(PyObject *object, char *method_name, char *arg_format, ...); This works for any object that has methods -- whether built-in or user-defined. You are responsible for eventually ``Py_DECREF``'ing the return value. To call, e.g., a file object's "seek" method with arguments 10, 0 (assuming the file object pointer is "f"):: res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0); if (res == NULL) { ... an exception occurred ... } else { Py_DECREF(res); } Note that since ``PyObject_CallObject()`` *always* wants a tuple for the argument list, to call a function without arguments, pass "()" for the format, and to call a function with one argument, surround the argument in parentheses, e.g. "(i)". How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)? ----------------------------------------------------------------------------------------------- In Python code, define an object that supports the ``write()`` method. Assign this object to ``sys.stdout`` and ``sys.stderr``. Call print_error, or just allow the standard traceback mechanism to work. Then, the output will go wherever your ``write()`` method sends it. The easiest way to do this is to use the StringIO class in the standard library. Sample code and use for catching stdout:: >>> class StdoutCatcher: ... def __init__(self): ... self.data = '' ... def write(self, stuff): ... self.data = self.data + stuff ... >>> import sys >>> sys.stdout = StdoutCatcher() >>> print 'foo' >>> print 'hello world!' >>> sys.stderr.write(sys.stdout.data) foo hello world! How do I access a module written in Python from C? --------------------------------------------------------- You can get a pointer to the module object as follows:: module = PyImport_ImportModule(""); If the module hasn't been imported yet (i.e. it is not yet present in ``sys.modules``), this initializes the module; otherwise it simply returns the value of ``sys.modules[""]``. Note that it doesn't enter the module into any namespace -- it only ensures it has been initialized and is stored in ``sys.modules``. You can then access the module's attributes (i.e. any name defined in the module) as follows:: attr = PyObject_GetAttrString(module, ""); Calling ``PyObject_SetAttrString()`` to assign to variables in the module also works. How do I interface to C++ objects from Python? ------------------------------------------------------ Depending on your requirements, there are many approaches. To do this manually, begin by reading `the "Extending and Embedding" document `_. Realize that for the Python run-time system, there isn't a whole lot of difference between C and C++ -- so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects. For C++ libraries, you can look at `SIP `_, `CXX `_, `Boost `_, or `Weave `_. `SWIG `_ is a similar automated tool that only supports C libraries. I added a module using the Setup file and the make fails; why? ---------------------------------------------------------------------- Setup must end in a newline, if there is no newline there, the build process fails. (Fixing this requires some ugly shell script hackery, and this bug is so minor that it doesn't seem worth the effort.) How do I debug an extension? ------------------------------------ When using GDB with dynamically loaded extensions, you can't set a breakpoint in your extension until your extension is loaded. In your ``.gdbinit`` file (or interactively), add the command:: br _PyImport_LoadDynamicModule Then, when you run GDB:: $ gdb /local/bin/python gdb) run myscript.py gdb) continue # repeat until your extension is loaded gdb) finish # so that your extension is loaded gdb) br myfunction.c:50 gdb) continue I want to compile a Python module on my Linux system, but some files are missing. Why? ------------------------------------------------------------------------------------------------- Most packaged versions of Python don't include the /usr/lib/python2.x/config/ directory, which contains various files required for compiling Python extensions. For Red Hat, install the python-devel RPM to get the necessary files. For Debian, run ``apt-get install python-dev``. What does "SystemError: _PyImport_FixupExtension: module yourmodule not loaded" mean? ------------------------------------------------------------------------------------------------------- This means that you have created an extension module named "yourmodule", but your module init function does not initialize with that name. Every module init function will have a line similar to:: module = Py_InitModule("yourmodule", yourmodule_functions); If the string passed to this function is not the same name as your extenion module, the ``SystemError`` exception will be raised. How do I tell "incomplete input" from "invalid input"? -------------------------------------------------------------------------------- Sometimes you want to emulate the Python interactive interpreter's behavior, where it gives you a continuation prompt when the input is incomplete (e.g. you typed the start of an "if" statement or you didn't close your parentheses or triple string quotes), but it gives you a syntax error message immediately when the input is invalid. In Python you can use the ``codeop`` module, which approximates the parser's behavior sufficiently. IDLE uses this, for example. The easiest way to do it in C is to call ``PyRun_InteractiveLoop()`` (perhaps in a separate thread) and let the Python interpreter handle the input for you. You can also set the ``PyOS_ReadlineFunctionPointer`` to point at your custom input function. See ``Modules/readline.c`` and ``Parser/myreadline.c`` for more hints. However sometimes you have to run the embedded Python interpreter in the same thread as your rest application and you can't allow the ``PyRun_InteractiveLoop()`` to stop while waiting for user input. The one solution then is to call ``PyParser_ParseString()`` and test for ``e.error`` equal to ``E_EOF``, which means the input is incomplete). Here's a sample code fragment, untested, inspired by code from Alex Farber:: #include #include #include #include #include #include int testcomplete(char *code) /* code should end in \n */ /* return -1 for error, 0 for incomplete, 1 for complete */ { node *n; perrdetail e; n = PyParser_ParseString(code, &_PyParser_Grammar, Py_file_input, &e); if (n == NULL) { if (e.error == E_EOF) return 0; return -1; } PyNode_Free(n); return 1; } Another solution is trying to compile the received string with ``Py_CompileString()``. If it compiles without errors, try to execute the returned code object by calling ``PyEval_EvalCode()``. Otherwise save the input for later. If the compilation fails, find out if it's an error or just more input is required - by extracting the message string from the exception tuple and comparing it to the string "unexpected EOF while parsing". Here is a complete example using the GNU readline library (you may want to ignore SIGINT while calling readline()):: #include #include #include #include #include #include int main (int argc, char* argv[]) { int i, j, done = 0; /* lengths of line, code */ char ps1[] = ">>> "; char ps2[] = "... "; char *prompt = ps1; char *msg, *line, *code = NULL; PyObject *src, *glb, *loc; PyObject *exc, *val, *trb, *obj, *dum; Py_Initialize (); loc = PyDict_New (); glb = PyDict_New (); PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ()); while (!done) { line = readline (prompt); if (NULL == line) /* CTRL-D pressed */ { done = 1; } else { i = strlen (line); if (i > 0) add_history (line); /* save non-empty lines */ if (NULL == code) /* nothing in code yet */ j = 0; else j = strlen (code); code = realloc (code, i + j + 2); if (NULL == code) /* out of memory */ exit (1); if (0 == j) /* code was empty, so */ code[0] = '\0'; /* keep strncat happy */ strncat (code, line, i); /* append line to code */ code[i + j] = '\n'; /* append '\n' to code */ code[i + j + 1] = '\0'; src = Py_CompileString (code, "", Py_single_input); if (NULL != src) /* compiled just fine - */ { if (ps1 == prompt || /* ">>> " or */ '\n' == code[i + j - 1]) /* "... " and double '\n' */ { /* so execute it */ dum = PyEval_EvalCode ((PyCodeObject *)src, glb, loc); Py_XDECREF (dum); Py_XDECREF (src); free (code); code = NULL; if (PyErr_Occurred ()) PyErr_Print (); prompt = ps1; } } /* syntax error or E_EOF? */ else if (PyErr_ExceptionMatches (PyExc_SyntaxError)) { PyErr_Fetch (&exc, &val, &trb); /* clears exception! */ if (PyArg_ParseTuple (val, "sO", &msg, &obj) && !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */ { Py_XDECREF (exc); Py_XDECREF (val); Py_XDECREF (trb); prompt = ps2; } else /* some other syntax error */ { PyErr_Restore (exc, val, trb); PyErr_Print (); free (code); code = NULL; prompt = ps1; } } else /* some non-syntax error */ { PyErr_Print (); free (code); code = NULL; prompt = ps1; } free (line); } } Py_XDECREF(glb); Py_XDECREF(loc); Py_Finalize(); exit(0); } How do I find undefined g++ symbols __builtin_new or __pure_virtual? ----------------------------------------------------------------------------------- To dynamically load g++ extension modules, you must recompile Python, relink it using g++ (change LINKCC in the python Modules Makefile), and link your extension module using g++ (e.g., "g++ -shared -o mymodule.so mymodule.o"). Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)? ----------------------------------------------------------------------------------------------------------------------------------------------------- In Python 2.2, you can inherit from builtin classes such as int, list, dict, etc. The Boost Python Library (BPL, http://www.boost.org/libs/python/doc/index.html) provides a way of doing this from C++ (i.e. you can inherit from an extension class written in C++ using the BPL). When importing module X, why do I get "undefined symbol: PyUnicodeUCS2*"? -------------------------------------------------------------------------------------------------- You are using a version of Python that uses a 4-byte representation for Unicode characters, but some C extension module you are importing was compiled using a Python that uses a 2-byte representation for Unicode characters (the default). If instead the name of the undefined symbol starts with ``PyUnicodeUCS4``, the problem is the reverse: Python was built using 2-byte Unicode characters, and the extension module was compiled using a Python with 4-byte Unicode characters. This can easily occur when using pre-built extension packages. RedHat Linux 7.x, in particular, provided a "python2" binary that is compiled with 4-byte Unicode. This only causes the link failure if the extension uses any of the ``PyUnicode_*()`` functions. It is also a problem if an extension uses any of the Unicode-related format specifiers for ``Py_BuildValue`` (or similar) or parameter specifications for ``PyArg_ParseTuple()``. You can check the size of the Unicode character a Python interpreter is using by checking the value of sys.maxunicode:: >>> import sys >>> if sys.maxunicode > 65535: ... print 'UCS4 build' ... else: ... print 'UCS2 build' The only way to solve this problem is to use extension modules compiled with a Python binary built using the same size for Unicode characters. python3-defaults-3.6.7/faq/general.ht0000664000000000000000000017123513305601050014353 0ustar Title: General Python FAQ Content-type: text/x-rst ==================================== General Python FAQ ==================================== :Date: $Date: 2006-02-26 06:15:13 +0100 (Sun, 26 Feb 2006) $ :Version: $Revision: 8958 $ :Web site: http://www.python.org/ .. contents:: .. sectnum:: General Information ===================== What is Python? ---------------------- Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2. To find out more, start with the `Beginner's Guide to Python `_. Why was Python created in the first place? -------------------------------------------------- Here's a *very* brief summary of what started it all, written by Guido van Rossum: I had extensive experience with implementing an interpreted language in the ABC group at CWI, and from working with this group I had learned a lot about language design. This is the origin of many Python features, including the use of indentation for statement grouping and the inclusion of very-high-level data types (although the details are all different in Python). I had a number of gripes about the ABC language, but also liked many of its features. It was impossible to extend the ABC language (or its implementation) to remedy my complaints -- in fact its lack of extensibility was one of its biggest problems. I had some experience with using Modula-2+ and talked with the designers of Modula-3 and read the Modula-3 report. Modula-3 is the origin of the syntax and semantics used for exceptions, and some other Python features. I was working in the Amoeba distributed operating system group at CWI. We needed a better way to do system administration than by writing either C programs or Bourne shell scripts, since Amoeba had its own system call interface which wasn't easily accessible from the Bourne shell. My experience with error handling in Amoeba made me acutely aware of the importance of exceptions as a programming language feature. It occurred to me that a scripting language with a syntax like ABC but with access to the Amoeba system calls would fill the need. I realized that it would be foolish to write an Amoeba-specific language, so I decided that I needed a language that was generally extensible. During the 1989 Christmas holidays, I had a lot of time on my hand, so I decided to give it a try. During the next year, while still mostly working on it in my own time, Python was used in the Amoeba project with increasing success, and the feedback from colleagues made me add many early improvements. In February 1991, after just over a year of development, I decided to post to USENET. The rest is in the Misc/HISTORY file. What is Python good for? -------------------------------- Python is a high-level general-purpose programming language that can be applied to many different classes of problems. The language comes with a large standard library that covers areas such as string processing (regular expressions, Unicode, calculating differences between files), Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming), software engineering (unit testing, logging, profiling, parsing Python code), and operating system interfaces (system calls, filesystems, TCP/IP sockets). Look at the table of contents for `the Library Reference `_ to get an idea of what's available. A wide variety of third-party extensions are also available. Consult `the Python Package Index `_ to find packages of interest to you. How does the Python version numbering scheme work? ---------------------------------------------------------- Python versions are numbered A.B.C or A.B. A is the major version number -- it is only incremented for really major changes in the language. B is the minor version number, incremented for less earth-shattering changes. C is the micro-level -- it is incremented for each bugfix release. See `PEP 6 <../../peps/pep-0006.html>`_ for more information about bugfix releases. Not all releases are bugfix releases. In the run-up to a new major release, a series of development releases are made, denoted as alpha, beta, or release candidate. Alphas are early releases in which interfaces aren't yet finalized; it's not unexpected to see an interface change between two alpha releases. Betas are more stable, preserving existing interfaces but possibly adding new modules, and release candidates are frozen, making no changes except as needed to fix critical bugs. Alpha, beta and release candidate versions have an additional suffix. The suffix for an alpha version is "aN" for some small number N, the suffix for a beta version is "bN" for some small number N, and the suffix for a release candidate version is "cN" for some small number N. In other words, all versions labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled 2.0cN, and *those* precede 2.0. You may also find version numbers with a "+" suffix, e.g. "2.2+". These are unreleased versions, built directly from the subversion trunk. In practice, after a final minor release is made, the subversion trunk is incremented to the next minor version, which becomes the "a0" version, e.g. "2.4a0". See also the documentation for ``sys.version``, ``sys.hexversion``, and ``sys.version_info``. Are there copyright restrictions on the use of Python? -------------------------------------------------------------- Not really. You can do anything you want with the source, as long as you leave the copyrights in and display those copyrights in any documentation about Python that you produce. If you honor the copyright rules, it's OK to use Python for commercial use, to sell copies of Python in source or binary form (modified or unmodified), or to sell products that incorporate Python in some form. We would still like to know about all commercial use of Python, of course. See `the PSF license page <../../psf/license.html>`_ to find further explanations and a link to the full text of the license. How do I obtain a copy of the Python source? --------------------------------------------------- The latest Python source distribution is always available from python.org, at http://www.python.org/download/. The latest development sources can be obtained via anonymous subversion from SourceForge, at http://svn.python.org/projects/python/trunk. The source distribution is a gzipped tar file containing the complete C source, LaTeX documentation, Python library modules, example programs, and several useful pieces of freely distributable software. This will compile and run out of the box on most UNIX platforms. Older versions of Python are also available from python.org. How do I get documentation on Python? -------------------------------------------- All documentation is available on-line, starting at http://www.python.org/doc/. The standard documentation for the current stable version of Python is also available at http://docs.python.org/. The LaTeX source for the documentation is part of the source distribution. If you don't have LaTeX, the latest Python documentation set is available by anonymous FTP in various formats such as PostScript and HTML. Visit the above URL for links to the current versions. I've never programmed before. Is there a Python tutorial? ----------------------------------------------------------------- There are numerous tutorials and books available. Consult `the Beginner's Guide `_ to find information for beginning Python programmers, including lists of tutorials. Are there other FTP sites that mirror the Python distribution? --------------------------------------------------------------------- Consult the list of python.org mirrors at http://www.python.org/Mirrors.html. Is there a newsgroup or mailing list devoted to Python? -------------------------------------------------------------- There is a newsgroup, comp.lang.python, and a mailing list, `python-list `_. The newsgroup and mailing list are gatewayed into each other -- if you can read news it's unnecessary to subscribe to the mailing list. comp.lang.python is high-traffic, receiving hundreds of postings every day, and Usenet readers are often more able to cope with this volume. Announcements of new software releases and events can be found in comp.lang.python.announce, a low-traffic moderated list that receives about five postings per day. It's available as `the python-announce mailing list `_. More info about other mailing lists and newsgroups can be found at http://www.python.org/community/lists.html. How do I get a beta test version of Python? --------------------------------------------------- All releases, including alphas, betas and release candidates, are announced on the comp.lang.python and comp.lang.python.announce newsgroups. All announcements also appear on the Python home page, at http://www.python.org/; an RSS feed of news is available. You can also access the development version of Python through subversion. See http://www.python.org/dev/devfaq.html#subversion-svn for details. How do I submit bug reports and patches for Python? ---------------------------------------------------------- To report a bug or submit a patch, please use the relevant service from the Python project at SourceForge. Bugs: http://sourceforge.net/tracker/?group_id=5470&atid=105470 Patches: http://sourceforge.net/tracker/?group_id=5470&atid=305470 You must have a SourceForge account to report bugs; this makes it possible for us to contact you if we have follow-up questions. It will also enable SourceForge to send you updates as we act on your bug. For more information on how Python is developed, consult `the Python Developer's Guide <../../dev/>`_. Are there any published articles about Python that I can reference? --------------------------------------------------------------------------- It's probably best to reference your favorite book about Python. The very first article about Python is this very old article that's now quite outdated. Guido van Rossum and Jelke de Boer, "Interactively Testing Remote Servers Using the Python Programming Language", CWI Quarterly, Volume 4, Issue 4 (December 1991), Amsterdam, pp 283-303. Are there any books on Python? ------------------------------------- Yes, there are many, and more are being published. See the python.org Wiki at http://www.python.org/moin/PythonBooks for a list. You can also search online bookstores for "Python" and filter out the Monty Python references; or perhaps search for "Python" and "language". Where in the world is www.python.org located? ----------------------------------------------------- It's currently in Amsterdam, graciously hosted by `XS4ALL `_. Thanks to Thomas Wouters for his work in arranging python.org's hosting. Why is it called Python? ------------------------------- At the same time he began implementing Python, Guido van Rossum was also reading the published scripts from "Monty Python's Flying Circus" (a BBC comedy series from the seventies, in the unlikely case you didn't know). It occurred to him that he needed a name that was short, unique, and slightly mysterious, so he decided to call the language Python. Do I have to like "Monty Python's Flying Circus"? ------------------------------------------------------------------- No, but it helps. :) Python in the real world ============================ How stable is Python? ---------------------------- Very stable. New, stable releases have been coming out roughly every 6 to 18 months since 1991, and this seems likely to continue. Currently there are usually around 18 months between major releases. With the introduction of retrospective "bugfix" releases the stability of existing releases is being improved. Bugfix releases, indicated by a third component of the version number (e.g. 2.1.3, 2.2.2), are managed for stability; only fixes for known problems are included in a bugfix release, and it's guaranteed that interfaces will remain the same throughout a series of bugfix releases. The `2.4.2 release <../../2.4.2/>`_ is the most stable version at this point in time. How many people are using Python? ---------------------------------------- Probably tens of thousands of users, though it's difficult to obtain an exact count. Python is available for free download, so there are no sales figures, and it's available from many different sites and packaged with many Linux distributions, so download statistics don't tell the whole story either. The comp.lang.python newsgroup is very active, but not all Python users post to the group or even read it. Overall there is no accurate estimate of the number of subscribers or Python users. Have any significant projects been done in Python? --------------------------------------------------------- See http://www.pythonology.org/success for a list of projects that use Python. Consulting the proceedings for `past Python conferences <../../workshops/>`_ will reveal contributions from many different companies and organizations. High-profile Python projects include `the Mailman mailing list manager `_ and `the Zope application server `_. Several Linux distributions, most notably `Red Hat `_, have written part or all of their installer and system administration software in Python. Companies that use Python internally include Google, Yahoo, and Industrial Light & Magic. What new developments are expected for Python in the future? ------------------------------------------------------------------- See http://www.python.org/peps for the Python Enhancement Proposals (PEPs). PEPs are design documents describing a suggested new feature for Python, providing a concise technical specification and a rationale. `PEP 1 <../../peps/pep-0001.html>`_ explains the PEP process and PEP format; read it first if you want to submit a PEP. New developments are discussed on `the python-dev mailing list `_. Is it reasonable to propose incompatible changes to Python? ------------------------------------------------------------------ In general, no. There are already millions of lines of Python code around the world, so any change in the language that invalidates more than a very small fraction of existing programs has to be frowned upon. Even if you can provide a conversion program, there still is the problem of updating all documentation; many books have been written about Python, and we don't want to invalidate them all at a single stroke. Providing a gradual upgrade path is necessary if a feature has to be changed. `PEP 5 <../../peps/pep-0005.html>`_ describes the procedure followed for introducing backward-incompatible changes while minimizing disruption for users. What is the Python Software Foundation? ----------------------------------------- The Python Software Foundation is an independent non-profit organization that holds the copyright on Python versions 2.1 and newer. The PSF's mission is to advance open source technology related to the Python programming language and to publicize the use of Python. The PSF's home page is at http://www.python.org/psf/. Donations to the PSF are tax-exempt in the US. If you use Python and find it helpful, please contribute via `the PSF donation page <../../psf/donations.html>`_. Is Python Y2K (Year 2000) Compliant? -------------------------------------------- As of August, 2003 no major problems have been reported and Y2K compliance seems to be a non-issue. Python does very few date calculations and for those it does perform relies on the C library functions. Python generally represents times either as seconds since 1970 or as a ``(year, month, day, ...)`` tuple where the year is expressed with four digits, which makes Y2K bugs unlikely. So as long as your C library is okay, Python should be okay. Of course, it's possible that a particular application written in Python makes assumptions about 2-digit years. Because Python is available free of charge, there are no absolute guarantees. If there *are* unforseen problems, liability is the user's problem rather than the developers', and there is nobody you can sue for damages. The Python copyright notice contains the following disclaimer: 4. PSF is making Python 2.3 available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.3 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.3, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. The good news is that *if* you encounter a problem, you have full source available to track it down and fix it. This is one advantage of an open source programming environment. Is Python a good language for beginning programmers? ----------------------------------------------------------------------- Yes. If you want to discuss Python's use in education, then you may be interested in joining `the edu-sig mailing list <../../sigs/edu-sig>`_. It is still common to start students with a procedural (subset of a) statically typed language such as Pascal, C, or a subset of C++ or Java. Students may be better served by learning Python as their first language. Python has a very simple and consistent syntax and a large standard library and, most importantly, using Python in a beginning programming course permits students to concentrate on important programming skills such as problem decomposition and data type design. With Python, students can be quickly introduced to basic concepts such as loops and procedures. They can even probably work with user-defined objects in their very first course. For a student who has never programmed before, using a statically typed language seems unnatural. It presents additional complexity that the student must master and slows the pace of the course. The students are trying to learn to think like a computer, decompose problems, design consistent interfaces, and encapsulate data. While learning to use a statically typed language is important in the long term, it is not necessarily the best topic to address in the students' first programming course. Many other aspects of Python make it a good first language. Like Java, Python has a large standard library so that students can be assigned programming projects very early in the course that *do* something. Assignments aren't restricted to the standard four-function calculator and check balancing programs. By using the standard library, students can gain the satisfaction of working on realistic applications as they learn the fundamentals of programming. Using the standard library also teaches students about code reuse. Third-party modules such as PyGame are also helpful in extending the students' reach. Python's interactive interpreter enables students to test language features while they're programming. They can keep a window with the interpreter running while they enter their program's source in another window. If they can't remember the methods for a list, they can do something like this:: >>> L = [] >>> dir(L) ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> help(L.append) Help on built-in function append: append(...) L.append(object) -- append object to end >>> L.append(1) >>> L [1] With the interpreter, documentation is never far from the student as he's programming. There are also good IDEs for Python. IDLE is a cross-platform IDE for Python that is written in Python using Tkinter. PythonWin is a Windows-specific IDE. Emacs users will be happy to know that there is a very good Python mode for Emacs. All of these programming environments provide syntax highlighting, auto-indenting, and access to the interactive interpreter while coding. Consult http://www.python.org/editors/ for a full list of Python editing environments. Upgrading Python ===================== What is this bsddb185 module my application keeps complaining about? -------------------------------------------------------------------- Starting with Python2.3, the distribution includes the `PyBSDDB package ` as a replacement for the old bsddb module. It includes functions which provide backward compatibility at the API level, but requires a newer version of the underlying `Berkeley DB `_ library. Files created with the older bsddb module can't be opened directly using the new module. Using your old version of Python and a pair of scripts which are part of Python 2.3 (db2pickle.py and pickle2db.py, in the Tools/scripts directory) you can convert your old database files to the new format. Using your old Python version, run the db2pickle.py script to convert it to a pickle, e.g.:: python2.2 /db2pickley.py database.db database.pck Rename your database file:: mv database.db olddatabase.db Now convert the pickle file to a new format database:: python2.3 /pickle2db.py database.db database.pck The precise commands you use will vary depending on the particulars of your installation. For full details about operation of these two scripts check the doc string at the start of each one. Python's Design ===================== Why does Python use indentation for grouping of statements? ----------------------------------------------------------- Guido van Rossum believes that using indentation for grouping is extremely elegant and contributes a lot to the clarity of the average Python program. Most people learn to love this feature after awhile. Since there are no begin/end brackets there cannot be a disagreement between grouping perceived by the parser and the human reader. Occasionally C programmers will encounter a fragment of code like this:: if (x <= y) x++; y--; z++; Only the ``x++`` statement is executed if the condition is true, but the indentation leads you to believe otherwise. Even experienced C programmers will sometimes stare a long time at it wondering why y is being decremented even for ``x > y``. Because there are no begin/end brackets, Python is much less prone to coding-style conflicts. In C there are many different ways to place the braces. If you're used to reading and writing code that uses one style, you will feel at least slightly uneasy when reading (or being required to write) another style. Many coding styles place begin/end brackets on a line by themself. This makes programs considerably longer and wastes valuable screen space, making it harder to get a good overview of a program. Ideally, a function should fit on onescreen (say, 20-30 lines). 20 lines of Python can do a lot more work than 20 lines of C. This is not solely due to the lack of begin/end brackets -- the lack of declarations and the high-level data types are also responsible -- but the indentation-based syntax certainly helps. Why am I getting strange results with simple arithmetic operations? ------------------------------------------------------------------- See the next question. Why are floating point calculations so inaccurate? -------------------------------------------------- People are often very surprised by results like this:: >>> 1.2-1.0 0.199999999999999996 and think it is a bug in Python. It's not. It's a problem caused by the internal representation of floating point numbers, which uses a fixed number of binary digits to represent a decimal number. Some decimal numbers can't be represented exactly in binary, resulting in small roundoff errors. In decimal math, there are many numbers that can't be represented with a fixed number of decimal digits, e.g. 1/3 = 0.3333333333....... In base 2, 1/2 = 0.1, 1/4 = 0.01, 1/8 = 0.001, etc. .2 equals 2/10 equals 1/5, resulting in the binary fractional number 0.001100110011001... Floating point numbers only have 32 or 64 bits of precision, so the digits are cut off at some point, and the resulting number is 0.199999999999999996 in decimal, not 0.2. A floating point's ``repr()`` function prints as many digits are necessary to make ``eval(repr(f)) == f`` true for any float f. The ``str()`` function prints fewer digits and this often results in the more sensible number that was probably intended:: >>> 0.2 0.20000000000000001 >>> print 0.2 0.2 Again, this has nothing to do with Python, but with the way the underlying C platform handles floating point numbers, and ultimately with the inaccuracy you'll always have when writing down numbers as a string of a fixed number of digits. One of the consequences of this is that it is dangerous to compare the result of some computation to a float with == ! Tiny inaccuracies may mean that == fails. Instead, you have to check that the difference between the two numbers is less than a certain threshold:: epsilon = 0.0000000000001 # Tiny allowed error expected_result = 0.4 if expected_result-epsilon <= computation() <= expected_result+epsilon: ... Please see the chapter on `floating point arithmetic `_ in the Python tutorial for more information. Why are Python strings immutable? --------------------------------- There are several advantages. One is performance: knowing that a string is immutable makes it easy to lay it out at construction time -- fixed and unchanging storage requirements. This is also one of the reasons for the distinction between tuples and lists. The other is that strings in Python are considered as "elemental" as numbers. No amount of activity will change the value 8 to anything else, and in Python, no amount of activity will change the string "eight" to anything else. Why must 'self' be used explicitly in method definitions and calls? ------------------------------------------------------------------- The idea was borrowed from Modula-3. It turns out to be very useful, for a variety of reasons. First, it's more obvious that you are using a method or instance attribute instead of a local variable. Reading ``self.x`` or ``self.meth()`` makes it absolutely clear that an instance variable or method is used even if you don't know the class definition by heart. In C++, you can sort of tell by the lack of a local variable declaration (assuming globals are rare or easily recognizable) -- but in Python, there are no local variable declarations, so you'd have to look up the class definition to be sure. Some C++ and Java coding standards call for instance attributes to have an ``m_`` prefix, so this explicitness is still useful in those languages, too. Second, it means that no special syntax is necessary if you want to explicitly reference or call the method from a particular class. In C++, if you want to use a method from a base class which is overridden in a derived class, you have to use the :: operator -- in Python you can write baseclass.methodname(self, ). This is particularly useful for __init__() methods, and in general in cases where a derived class method wants to extend the base class method of the same name and thus has to call the base class method somehow. Finally, for instance variables it solves a syntactic problem with assignment: since local variables in Python are (by definition!) those variables to which a value assigned in a function body (and that aren't explicitly declared global), there has to be some way to tell the interpreter that an assignment was meant to assign to an instance variable instead of to a local variable, and it should preferably be syntactic (for efficiency reasons). C++ does this through declarations, but Python doesn't have declarations and it would be a pity having to introduce them just for this purpose. Using the explicit "self.var" solves this nicely. Similarly, for using instance variables, having to write "self.var" means that references to unqualified names inside a method don't have to search the instance's directories. To put it another way, local variables and instance variables live in two different namespaces, and you need to tell Python which namespace to use. Why can't I use an assignment in an expression? ------------------------------------------------------- Many people used to C or Perl complain that they want to use this C idiom:: while (line = readline(f)) { ...do something with line... } where in Python you're forced to write this:: while True: line = f.readline() if not line: break ...do something with line... The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:: if (x = 0) { ...error handling... } else { ...code that only works for nonzero x... } The error is a simple typo: ``x = 0``, which assigns 0 to the variable ``x``, was written while the comparison ``x == 0`` is certainly what was intended. Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct. An interesting phenomenon is that most experienced Python programmers recognize the "while True" idiom and don't seem to be missing the assignment in expression construct much; it's only newcomers who express a strong desire to add this to the language. There's an alternative way of spelling this that seems attractive but is generally less robust than the "while True" solution:: line = f.readline() while line: ...do something with line... line = f.readline() The problem with this is that if you change your mind about exactly how you get the next line (e.g. you want to change it into ``sys.stdin.readline()``) you have to remember to change two places in your program -- the second occurrence is hidden at the bottom of the loop. The best approach is to use iterators, making it possible to loop through objects using the ``for`` statement. For example, in the current version of Python file objects support the iterator protocol, so you can now write simply:: for line in f: ... do something with line... Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))? ---------------------------------------------------------------------------------------------------------------- The major reason is history. Functions were used for those operations that were generic for a group of types and which were intended to work even for objects that didn't have methods at all (e.g. tuples). It is also convenient to have a function that can readily be applied to an amorphous collection of objects when you use the functional features of Python (``map()``, ``apply()`` et al). In fact, implementing ``len()``, ``max()``, ``min()`` as a built-in function is actually less code than implementing them as methods for each type. One can quibble about individual cases but it's a part of Python, and it's too late to make such fundamental changes now. The functions have to remain to avoid massive code breakage. Note that for string operations Python has moved from external functions (the ``string`` module) to methods. However, ``len()`` is still a function. Why is join() a string method instead of a list or tuple method? ---------------------------------------------------------------- Strings became much more like other standard types starting in Python 1.6, when methods were added which give the same functionality that has always been available using the functions of the string module. Most of these new methods have been widely accepted, but the one which appears to make some programmers feel uncomfortable is:: ", ".join(['1', '2', '4', '8', '16']) which gives the result:: "1, 2, 4, 8, 16" There are two usual arguments against this usage. The first runs along the lines of: "It looks really ugly using a method of a string literal (string constant)", to which the answer is that it might, but a string literal is just a fixed value. If the methods are to be allowed on names bound to strings there is no logical reason to make them unavailable on literals. The second objection is typically cast as: "I am really telling a sequence to join its members together with a string constant". Sadly, you aren't. For some reason there seems to be much less difficulty with having split() as a string method, since in that case it is easy to see that :: "1, 2, 4, 8, 16".split(", ") is an instruction to a string literal to return the substrings delimited by the given separator (or, by default, arbitrary runs of white space). In this case a Unicode string returns a list of Unicode strings, an ASCII string returns a list of ASCII strings, and everyone is happy. join() is a string method because in using it you are telling the separator string to iterate over an arbitrary sequence, forming string representations of each of the elements, and inserting itself between the elements' representations. This method can be used with any argument which obeys the rules for sequence objects, inluding any new classes you might define yourself. Because this is a string method it can work for Unicode strings as well as plain ASCII strings. If join() were a method of the sequence types then the sequence types would have to decide which type of string to return depending on the type of the separator. If none of these arguments persuade you, then for the moment you can continue to use the join() function from the string module, which allows you to write :: string.join(['1', '2', '4', '8', '16'], ", ") How fast are exceptions? ------------------------ A try/except block is extremely efficient. Actually executing an exception is expensive. In versions of Python prior to 2.0 it was common to use this idiom:: try: value = dict[key] except KeyError: dict[key] = getvalue(key) value = dict[key] This only made sense when you expected the dict to have the key almost all the time. If that wasn't the case, you coded it like this:: if dict.has_key(key): value = dict[key] else: dict[key] = getvalue(key) value = dict[key] (In Python 2.0 and higher, you can code this as ``value = dict.setdefault(key, getvalue(key))``.) Why isn't there a switch or case statement in Python? ----------------------------------------------------- You can do this easily enough with a sequence of ``if... elif... elif... else``. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. See `PEP 275 <../../peps/pep-0275.html>`_ for complete details and the current status. For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example:: def function_1 (...): ... functions = {'a': function_1, 'b': function_2, 'c': self.method_1, ...} func = functions[value] func() For calling methods on objects, you can simplify yet further by using the ``getattr()`` built-in to retrieve methods with a particular name:: def visit_a (self, ...): ... ... def dispatch (self, value): method_name = 'visit_' + str(value) method = getattr(self, method_name) method() It's suggested that you use a prefix for the method names, such as ``visit_`` in this example. Without such a prefix, if values are coming from an untrusted source, an attacker would be able to call any method on your object. Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation? -------------------------------------------------------------------------------------------------------- Answer 1: Unfortunately, the interpreter pushes at least one C stack frame for each Python stack frame. Also, extensions can call back into Python at almost random moments. Therefore, a complete threads implementation requires thread support for C. Answer 2: Fortunately, there is `Stackless Python `_, which has a completely redesigned interpreter loop that avoids the C stack. It's still experimental but looks very promising. Although it is binary compatible with standard Python, it's still unclear whether Stackless will make it into the core -- maybe it's just too revolutionary. Why can't lambda forms contain statements? ------------------------------------------ Python lambda forms cannot contain statements because Python's syntactic framework can't handle statements nested inside expressions. However, in Python, this is not a serious problem. Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you're too lazy to define a function. Functions are already first class objects in Python, and can be declared in a local scope. Therefore the only advantage of using a lambda form instead of a locally-defined function is that you don't need to invent a name for the function -- but that's just a local variable to which the function object (which is exactly the same type of object that a lambda form yields) is assigned! Can Python be compiled to machine code, C or some other language? ----------------------------------------------------------------- Not easily. Python's high level data types, dynamic typing of objects and run-time invocation of the interpreter (using ``eval()`` or ``exec``) together mean that a "compiled" Python program would probably consist mostly of calls into the Python run-time system, even for seemingly simple operations like ``x+1``. Several projects described in the Python newsgroup or at past `Python conferences <../../workshops/>`_ have shown that this approach is feasible, although the speedups reached so far are only modest (e.g. 2x). Jython uses the same strategy for compiling to Java bytecode. (Jim Hugunin has demonstrated that in combination with whole-program analysis, speedups of 1000x are feasible for small demo programs. See the proceedings from the `1997 Python conference <../../workshops/1997-10/proceedings/>`_ for more information.) Internally, Python source code is always translated into a bytecode representation, and this bytecode is then executed by the Python virtual machine. In order to avoid the overhead of repeatedly parsing and translating modules that rarely change, this byte code is written into a file whose name ends in ".pyc" whenever a module is parsed. When the corresponding .py file is changed, it is parsed and translated again and the .pyc file is rewritten. There is no performance difference once the .pyc file has been loaded, as the bytecode read from the .pyc file is exactly the same as the bytecode created by direct translation. The only difference is that loading code from a .pyc file is faster than parsing and translating a .py file, so the presence of precompiled .pyc files improves the start-up time of Python scripts. If desired, the Lib/compileall.py module can be used to create valid .pyc files for a given set of modules. Note that the main script executed by Python, even if its filename ends in .py, is not compiled to a .pyc file. It is compiled to bytecode, but the bytecode is not saved to a file. Usually main scripts are quite short, so this doesn't cost much speed. There are also several programs which make it easier to intermingle Python and C code in various ways to increase performance. See, for example, `Psyco `_, `Pyrex `_, `PyInline `_, `Py2Cmod `_, and `Weave `_. How does Python manage memory? ------------------------------ The details of Python memory management depend on the implementation. The standard C implementation of Python uses reference counting to detect inaccessible objects, and another mechanism to collect reference cycles, periodically executing a cycle detection algorithm which looks for inaccessible cycles and deletes the objects involved. The ``gc`` module provides functions to perform a garbage collection, obtain debugging statistics, and tune the collector's parameters. Jython relies on the Java runtime so the JVM's garbage collector is used. This difference can cause some subtle porting problems if your Python code depends on the behavior of the reference counting implementation. Sometimes objects get stuck in tracebacks temporarily and hence are not deallocated when you might expect. Clear the tracebacks with:: import sys sys.exc_clear() sys.exc_traceback = sys.last_traceback = None Tracebacks are used for reporting errors, implementing debuggers and related things. They contain a portion of the program state extracted during the handling of an exception (usually the most recent exception). In the absence of circularities and tracebacks, Python programs need not explicitly manage memory. Why doesn't Python use a more traditional garbage collection scheme? For one thing, this is not a C standard feature and hence it's not portable. (Yes, we know about the Boehm GC library. It has bits of assembler code for *most* common platforms, not for all of them, and although it is mostly transparent, it isn't completely transparent; patches are required to get Python to work with it.) Traditional GC also becomes a problem when Python is embedded into other applications. While in a standalone Python it's fine to replace the standard malloc() and free() with versions provided by the GC library, an application embedding Python may want to have its *own* substitute for malloc() and free(), and may not want Python's. Right now, Python works with anything that implements malloc() and free() properly. In Jython, the following code (which is fine in CPython) will probably run out of file descriptors long before it runs out of memory:: for file in : f = open(file) c = f.read(1) Using the current reference counting and destructor scheme, each new assignment to f closes the previous file. Using GC, this is not guaranteed. If you want to write code that will work with any Python implementation, you should explicitly close the file; this will work regardless of GC:: for file in : f = open(file) c = f.read(1) f.close() Why isn't all memory freed when Python exits? ----------------------------------------------------- Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. There are also certain bits of memory that are allocated by the C library that are impossible to free (e.g. a tool like Purify will complain about these). Python is, however, aggressive about cleaning up memory on exit and does try to destroy every single object. If you want to force Python to delete certain things on deallocation use the ``sys.exitfunc()`` hook to run a function that will force those deletions. Why are there separate tuple and list data types? ------------------------------------------------- Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers. Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one. For example, ``os.listdir('.')`` returns a list of strings representing the files in the current directory. Functions which operate on this output would generally not break if you added another file or two to the directory. Tuples are immutable, meaning that once a tuple has been created, you can't replace any of its elements with a new value. Lists are mutable, meaning that you can always change a list's elements. Only immutable elements can be used as dictionary keys, and hence only tuples and not lists can be used as keys. How are lists implemented? -------------------------- Python's lists are really variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array and the array's length in a list head structure. This makes indexing a list ``a[i]`` an operation whose cost is independent of the size of the list or the value of the index. When items are appended or inserted, the array of references is resized. Some cleverness is applied to improve the performance of appending items repeatedly; when the array must be grown, some extra space is allocated so the next few times don't require an actual resize. How are dictionaries implemented? ----------------------------------------- Python's dictionaries are implemented as resizable hash tables. Compared to B-trees, this gives better performance for lookup (the most common operation by far) under most circumstances, and the implementation is simpler. Dictionaries work by computing a hash code for each key stored in the dictionary using the ``hash()`` built-in function. The hash code varies widely depending on the key; for example, "Python" hashes to -539294296 while "python", a string that differs by a single bit, hashes to 1142331976. The hash code is then used to calculate a location in an internal array where the value will be stored. Assuming that you're storing keys that all have different hash values, this means that dictionaries take constant time -- O(1), in computer science notation -- to retrieve a key. It also means that no sorted order of the keys is maintained, and traversing the array as the ``.keys()`` and ``.items()`` do will output the dictionary's content in some arbitrary jumbled order. Why must dictionary keys be immutable? ---------------------------------------------- The hash table implementation of dictionaries uses a hash value calculated from the key value to find the key. If the key were a mutable object, its value could change, and thus its hash could also change. But since whoever changes the key object can't tell that it was being used as a dictionary key, it can't move the entry around in the dictionary. Then, when you try to look up the same object in the dictionary it won't be found because its hash value is different. If you tried to look up the old value it wouldn't be found either, because the value of the object found in that hash bin would be different. If you want a dictionary indexed with a list, simply convert the list to a tuple first; the function ``tuple(L)`` creates a tuple with the same entries as the list ``L``. Tuples are immutable and can therefore be used as dictionary keys. Some unacceptable solutions that have been proposed: - Hash lists by their address (object ID). This doesn't work because if you construct a new list with the same value it won't be found; e.g.:: d = {[1,2]: '12'} print d[[1,2]] would raise a KeyError exception because the id of the ``[1,2]`` used in the second line differs from that in the first line. In other words, dictionary keys should be compared using ``==``, not using 'is'. - Make a copy when using a list as a key. This doesn't work because the list, being a mutable object, could contain a reference to itself, and then the copying code would run into an infinite loop. - Allow lists as keys but tell the user not to modify them. This would allow a class of hard-to-track bugs in programs when you forgot or modified a list by accident. It also invalidates an important invariant of dictionaries: every value in ``d.keys()`` is usable as a key of the dictionary. - Mark lists as read-only once they are used as a dictionary key. The problem is that it's not just the top-level object that could change its value; you could use a tuple containing a list as a key. Entering anything as a key into a dictionary would require marking all objects reachable from there as read-only -- and again, self-referential objects could cause an infinite loop. There is a trick to get around this if you need to, but use it at your own risk: You can wrap a mutable structure inside a class instance which has both a __cmp__ and a __hash__ method. You must then make sure that the hash value for all such wrapper objects that reside in a dictionary (or other hash based structure), remain fixed while the object is in the dictionary (or other structure).:: class ListWrapper: def __init__(self, the_list): self.the_list = the_list def __cmp__(self, other): return self.the_list == other.the_list def __hash__(self): l = self.the_list result = 98767 - len(l)*555 for i in range(len(l)): try: result = result + (hash(l[i]) % 9999999) * 1001 + i except: result = (result % 7777777) + i * 333 return result Note that the hash computation is complicated by the possibility that some members of the list may be unhashable and also by the possibility of arithmetic overflow. Furthermore it must always be the case that if ``o1 == o2`` (ie ``o1.__cmp__(o2)==0``) then ``hash(o1)==hash(o2)`` (ie, ``o1.__hash__() == o2.__hash__()``), regardless of whether the object is in a dictionary or not. If you fail to meet these restrictions dictionaries and other hash based structures will misbehave. In the case of ListWrapper, whenever the wrapper object is in a dictionary the wrapped list must not change to avoid anomalies. Don't do this unless you are prepared to think hard about the requirements and the consequences of not meeting them correctly. Consider yourself warned. Why doesn't list.sort() return the sorted list? ------------------------------------------------------- In situations where performance matters, making a copy of the list just to sort it would be wasteful. Therefore, list.sort() sorts the list in place. In order to remind you of that fact, it does not return the sorted list. This way, you won't be fooled into accidentally overwriting a list when you need a sorted copy but also need to keep the unsorted version around. In Python 2.4 a new builtin - sorted() - has been added. This function creates a new list from a passed iterable, sorts it and returns it. As a result, here's the idiom to iterate over the keys of a dictionary in sorted order:: for key in sorted(dict.iterkeys()): ...do whatever with dict[key]... Versions of Python prior to 2.4 need to use the following idiom:: keys = dict.keys() keys.sort() for key in keys: ...do whatever with dict[key]... How do you specify and enforce an interface spec in Python? ------------------------------------------------------------------- An interface specification for a module as provided by languages such as C++ and Java describes the prototypes for the methods and functions of the module. Many feel that compile-time enforcement of interface specifications help in the construction of large programs. Python does not support interface specifications directly, but many of their advantages can be obtained by an appropriate test discipline for components, which can often be very easily accomplished in Python. There is also a tool, PyChecker, which can be used to find problems due to subclassing. A good test suite for a module can at once provide a regression test and serve as both a module interface specification and a set of examples. Many Python modules can be run as a script to provide a simple "self test." Even modules which use complex external interfaces can often be tested in isolation using trivial "stub" emulations of the external interface. The ``doctest`` and ``unittest`` modules or third-party test frameworks can be used to construct exhaustive test suites that exercise every line of code in a module. An appropriate testing discipline can help build large complex applications in Python as well as having interface specifications would. In fact, it can be better because an interface specification cannot test certain properties of a program. For example, the ``append()`` method is expected to add new elements to the end of some internal list; an interface specification cannot test that your ``append()`` implementation will actually do this correctly, but it's trivial to check this property in a test suite. Writing test suites is very helpful, and you might want to design your code with an eye to making it easily tested. One increasingly popular technique, test-directed development, calls for writing parts of the test suite first, before you write any of the actual code. Of course Python allows you to be sloppy and not write test cases at all. Why are default values shared between objects? ---------------------------------------------------------------- This type of bug commonly bites neophyte programmers. Consider this function:: def foo(D={}): # Danger: shared reference to one dict for all calls ... compute something ... D[key] = value return D The first time you call this function, ``D`` contains a single item. The second time, ``D`` contains two items because when ``foo()`` begins executing, ``D`` starts out with an item already in it. It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object. By definition, immutable objects such as numbers, strings, tuples, and ``None``, are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion. Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use ``None`` as the default value and inside the function, check if the parameter is ``None`` and create a new list/dictionary/whatever if it is. For example, don't write:: def foo(dict={}): ... but:: def foo(dict=None): if dict is None: dict = {} # create a new dict for local namespace This feature can be useful. When you have a function that's time-consuming to compute, a common technique is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again. This is called "memoizing", and can be implemented like this:: # Callers will never provide a third parameter for this function. def expensive (arg1, arg2, _cache={}): if _cache.has_key((arg1, arg2)): return _cache[(arg1, arg2)] # Calculate the value result = ... expensive computation ... _cache[(arg1, arg2)] = result # Store result in the cache return result You could use a global variable containing a dictionary instead of the default value; it's a matter of taste. Why is there no goto? ------------------------ You can use exceptions to provide a "structured goto" that even works across function calls. Many feel that exceptions can conveniently emulate all reasonable uses of the "go" or "goto" constructs of C, Fortran, and other languages. For example:: class label: pass # declare a label try: ... if (condition): raise label() # goto label ... except label: # where to goto pass ... This doesn't allow you to jump into the middle of a loop, but that's usually considered an abuse of goto anyway. Use sparingly. Why do I get a SyntaxError for a 'continue' inside a 'try'? ------------------------------------------------------------------- This is an implementation limitation, caused by the extremely simple-minded way Python generates bytecode. The ``try`` block pushes something on the "block stack" which the ``continue`` would have to pop off again. The current code generator doesn't have the data structures around so that ``continue`` can generate the right code. Note that Jython doesn't have this restriction! Why can't raw strings (r-strings) end with a backslash? --------------------------------------------------------------- More precisely, they can't end with an odd number of backslashes: the unpaired backslash at the end escapes the closing quote character, leaving an unterminated string. Raw strings were designed to ease creating input for processors (chiefly regular expression engines) that want to do their own backslash escape processing. Such processors consider an unmatched trailing backslash to be an error anyway, so raw strings disallow that. In return, they allow you to pass on the string quote character by escaping it with a backslash. These rules work well when r-strings are used for their intended purpose. If you're trying to build Windows pathnames, note that all Windows system calls accept forward slashes too:: f = open("/mydir/file.txt") # works fine! If you're trying to build a pathname for a DOS command, try e.g. one of :: dir = r"\this\is\my\dos\dir" "\\" dir = r"\this\is\my\dos\dir\ "[:-1] dir = "\\this\\is\\my\\dos\\dir\\" Why doesn't Python have a "with" statement like some other languages? --------------------------------------------------------------------------------------- Because such a construct would be ambiguous. Some languages, such as Object Pascal, Delphi, and C++, use static types. So it is possible to know, in an unambiguous way, what member is being assigned in a "with" clause. This is the main point - the compiler *always* knows the scope of every variable at compile time. Python uses dynamic types. It is impossible to know in advance which attribute will be referenced at runtime. Member attributes may be added or removed from objects on the fly. This would make it impossible to know, from a simple reading, what attribute is being referenced - a local one, a global one, or a member attribute. For instance, take the following incomplete snippet:: def foo(a): with a: print x The snippet assumes that "a" must have a member attribute called "x". However, there is nothing in Python that guarantees that. What should happen if "a" is, let us say, an integer? And if I have a global variable named "x", will it end up being used inside the with block? As you see, the dynamic nature of Python makes such choices much harder. The primary benefit of "with" and similar language features (reduction of code volume) can, however, easily be achieved in Python by assignment. Instead of:: function(args).dict[index][index].a = 21 function(args).dict[index][index].b = 42 function(args).dict[index][index].c = 63 write this:: ref = function(args).dict[index][index] ref.a = 21 ref.b = 42 ref.c = 63 This also has the side-effect of increasing execution speed because name bindings are resolved at run-time in Python, and the second version only needs to perform the resolution once. If the referenced object does not have a, b and c attributes, of course, the end result is still a run-time exception. Why are colons required for the if/while/def/class statements? -------------------------------------------------------------------- The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:: if a==b print a versus :: if a==b: print a Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in the second line of this FAQ answer; it's a standard usage in English. Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text. python3-defaults-3.6.7/faq/gui.ht0000664000000000000000000001405313305601050013514 0ustar Title: Graphic User Interface FAQ Content-type: text/x-rst ==================================== Graphic User Interface FAQ ==================================== :Date: $Date: 2003-09-04 18:00:23 -0600 (Thu, 04 Sep 2003) $ :Version: $Revision: 6607 $ :Web site: http://www.python.org/ .. contents:: .. sectnum:: General GUI Questions ============================ What platform-independent GUI toolkits exist for Python? ---------------------------------------------------------------- Depending on what platform(s) you are aiming at, there are several. Tkinter '''''''''''' Standard builds of Python include an object-oriented interface to the Tcl/Tk widget set, called Tkinter. This is probably the easiest to install and use. For more info about Tk, including pointers to the source, see the Tcl/Tk home page at http://www.tcl.tk. Tcl/Tk is fully portable to the MacOS, Windows, and Unix platforms. wxWindows ''''''''''''' wxWindows is a portable GUI class library written in C++ that's a portable interface to various platform-specific libraries; wxPython is a Python interface to wxWindows. wxWindows supports Windows and MacOS; on Unix variants, it supports both GTk+ and Motif toolkits. wxWindows preserves the look and feel of the underlying graphics toolkit, and there is quite a rich widget set and collection of GDI classes. See `the wxWindows page `_ for more details. `wxPython `_ is an extension module that wraps many of the wxWindows C++ classes, and is quickly gaining popularity amongst Python developers. You can get wxPython as part of the source or CVS distribution of wxWindows, or directly from its home page. Qt '''''' There are bindings available for the Qt toolkit (`PyQt `_) and for KDE (PyKDE). If you're writing open source software, you don't need to pay for PyQt, but if you want to write proprietary applications, you must buy a PyQt license from `Riverbank Computing `_ and a Qt license from `Trolltech `_. GTk+ ''''''''''' PyGTk bindings for the `GTk+ toolkit `_ have been implemented by by James Henstridge; see ftp://ftp.gtk.org/pub/gtk/python/. FLTK ''''''''''' Python bindings for `the FLTK toolkit `_, a simple yet powerful and mature cross-platform windowing system, are available from `the PyFLTK project `_. FOX ''''''''''' A wrapper for `the FOX toolkit `_ called `FXpy `_ is available. FOX supports both Unix variants and Windows. OpenGL ''''''''''''' For OpenGL bindings, see `PyOpenGL `_. What platform-specific GUI toolkits exist for Python? ---------------------------------------------------------------- `The Mac port `_ by Jack Jansen has a rich and ever-growing set of modules that support the native Mac toolbox calls. The port includes support for MacOS9 and MacOS X's Carbon libraries. By installing the `PyObjc Objective-C bridge `_, Python programs can use MacOS X's Cocoa libraries. See the documentation that comes with the Mac port. `Pythonwin `_ by Mark Hammond includes an interface to the Microsoft Foundation Classes and a Python programming environment using it that's written mostly in Python. Tkinter questions ===================== How do I freeze Tkinter applications? --------------------------------------------- Freeze is a tool to create stand-alone applications. When freezing Tkinter applications, the applications will not be truly stand-alone, as the application will still need the Tcl and Tk libraries. One solution is to ship the application with the tcl and tk libraries, and point to them at run-time using the TCL_LIBRARY and TK_LIBRARY environment variables. To get truly stand-alone applications, the Tcl scripts that form the library have to be integrated into the application as well. One tool supporting that is SAM (stand-alone modules), which is part of the Tix distribution (http://tix.mne.com). Build Tix with SAM enabled, perform the appropriate call to Tclsam_init etc inside Python's Modules/tkappinit.c, and link with libtclsam and libtksam (you might include the Tix libraries as well). Can I have Tk events handled while waiting for I/O? ----------------------------------------------------------- Yes, and you don't even need threads! But you'll have to restructure your I/O code a bit. Tk has the equivalent of Xt's XtAddInput() call, which allows you to register a callback function which will be called from the Tk mainloop when I/O is possible on a file descriptor. Here's what you need:: from Tkinter import tkinter tkinter.createfilehandler(file, mask, callback) The file may be a Python file or socket object (actually, anything with a fileno() method), or an integer file descriptor. The mask is one of the constants tkinter.READABLE or tkinter.WRITABLE. The callback is called as follows:: callback(file, mask) You must unregister the callback when you're done, using :: tkinter.deletefilehandler(file) Note: since you don't know *how many bytes* are available for reading, you can't use the Python file object's read or readline methods, since these will insist on reading a predefined number of bytes. For sockets, the recv() or recvfrom() methods will work fine; for other files, use os.read(file.fileno(), maxbytecount). I can't get key bindings to work in Tkinter: why? --------------------------------------------------- An often-heard complaint is that event handlers bound to events with the bind() method don't get handled even when the appropriate key is pressed. The most common cause is that the widget to which the binding applies doesn't have "keyboard focus". Check out the Tk documentation for the focus command. Usually a widget is given the keyboard focus by clicking in it (but not for labels; see the takefocus option). python3-defaults-3.6.7/faq/installed.ht0000664000000000000000000000473313305601050014713 0ustar Title: "Why is Python Installed on my Computer?" FAQ Content-type: text/x-rst ===================================================== "Why is Python Installed on my Computer?" FAQ ===================================================== What is Python? ---------------------- Python is a programming language. It's used for many different applications. It's used in some high schools and colleges as an introductory programming language because Python is easy to learn, but it's also used by professional software developers at places such as Google, NASA, and Industrial Light & Magic. If you're curious about finding out more about Python, start with the `Beginner's Guide to Python `_. Why is Python installed on my machine? -------------------------------------------------- If you find Python installed on your system but don't remember installing it, there are several possible ways it could have gotten there. * Perhaps another user on the computer wanted to learn programming and installed it; you'll have to figure out who's been using the machine and might have installed it. * A third-party application installed on the machine might have been written in Python and included a Python installation. For a home computer, the most common such application is `PySol `_, a solitaire game that includes over 200 different games and variations. * Some Windows machines also have Python installed. At this writing we're aware of computers from Hewlett-Packard and Compaq that include Python. Apparently some of HP/Compaq's administrative tools are written in Python. * All Apple computers running Mac OS X have Python installed; it's included in the base installation. Can I delete Python? ---------------------------- That depends on where Python came from. If someone installed it deliberately, you can remove it without hurting anything. On Windows, use the Add/Remove Programs icon in the Control Panel. If Python was installed by a third-party application, you can also remove it, but that application will no longer work. You should probably use that application's uninstaller rather than removing Python directly. If Python came with your operating system, removing it is not recommended. If you remove it, whatever tools were written in Python will no longer run, and some of them might be important to you. Reinstalling the whole system would then be required to fix things again. python3-defaults-3.6.7/faq/library.ht0000664000000000000000000010306013305601050014371 0ustar Title: Python Library and Extension FAQ Content-type: text/x-rst ==================================== Python Library and Extension FAQ ==================================== :Date: $Date: 2005-12-16 19:21:20 -0700 (Fri, 16 Dec 2005) $ :Version: $Revision: 8684 $ :Web site: http://www.python.org/ .. contents:: .. sectnum:: General Library Questions =============================== How do I find a module or application to perform task X? ------------------------------------------------------------- Check `the Library Reference `_ to see if there's a relevant standard library module. (Eventually you'll learn what's in the standard library and will able to skip this step.) Search the `Python Package Index `_. Next, check the `Vaults of Parnassus `_, an older index of packages. Finally, try `Google `_ or other Web search engine. Searching for "Python" plus a keyword or two for your topic of interest will usually find something helpful. Where is the math.py (socket.py, regex.py, etc.) source file? --------------------------------------------------------------------- If you can't find a source file for a module it may be a builtin or dynamically loaded module implemented in C, C++ or other compiled language. In this case you may not have the source file or it may be something like mathmodule.c, somewhere in a C source directory (not on the Python Path). There are (at least) three kinds of modules in Python: 1) modules written in Python (.py); 2) modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc); 3) modules written in C and linked with the interpreter; to get a list of these, type:: import sys print sys.builtin_module_names How do I make a Python script executable on Unix? --------------------------------------------------------- You need to do two things: the script file's mode must be executable and the first line must begin with ``#!`` followed by the path of the Python interpreter. The first is done by executing ``chmod +x scriptfile`` or perhaps ``chmod 755 scriptfile``. The second can be done in a number of ways. The most straightforward way is to write :: #!/usr/local/bin/python as the very first line of your file, using the pathname for where the Python interpreter is installed on your platform. If you would like the script to be independent of where the Python interpreter lives, you can use the "env" program. Almost all Unix variants support the following, assuming the python interpreter is in a directory on the user's $PATH:: #! /usr/bin/env python *Don't* do this for CGI scripts. The $PATH variable for CGI scripts is often very minimal, so you need to use the actual absolute pathname of the interpreter. Occasionally, a user's environment is so full that the /usr/bin/env program fails; or there's no env program at all. In that case, you can try the following hack (due to Alex Rezinsky):: #! /bin/sh """:" exec python $0 ${1+"$@"} """ The minor disadvantage is that this defines the script's __doc__ string. However, you can fix that by adding :: __doc__ = """...Whatever...""" Is there a curses/termcap package for Python? ---------------------------------------------------- For Unix variants: The standard Python source distribution comes with a curses module in the Modules/ subdirectory, though it's not compiled by default (note that this is not available in the Windows distribution -- there is no curses module for Windows). The curses module supports basic curses features as well as many additional functions from ncurses and SYSV curses such as colour, alternative character set support, pads, and mouse support. This means the module isn't compatible with operating systems that only have BSD curses, but there don't seem to be any currently maintained OSes that fall into this category. For Windows: use `the consolelib module `_. Is there an equivalent to C's onexit() in Python? -------------------------------------------------------- `The atexit module `_ provides a register function that is similar to C's onexit. Why don't my signal handlers work? -------------------------------------------- The most common problem is that the signal handler is declared with the wrong argument list. It is called as :: handler(signum, frame) so it should be declared with two arguments:: def handler(signum, frame): ... Common tasks ================= How do I test a Python program or component? ---------------------------------------------------- Python comes with two testing frameworks. The `doctest module `_ finds examples in the docstrings for a module and runs them, comparing the output with the expected output given in the docstring. The `unittest module `_ is a fancier testing framework modelled on Java and Smalltalk testing frameworks. For testing, it helps to write the program so that it may be easily tested by using good modular design. Your program should have almost all functionality encapsulated in either functions or class methods -- and this sometimes has the surprising and delightful effect of making the program run faster (because local variable accesses are faster than global accesses). Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do. The "global main logic" of your program may be as simple as :: if __name__=="__main__": main_logic() at the bottom of the main module of your program. Once your program is organized as a tractable collection of functions and class behaviours you should write test functions that exercise the behaviours. A test suite can be associated with each module which automates a sequence of tests. This sounds like a lot of work, but since Python is so terse and flexible it's surprisingly easy. You can make coding much more pleasant and fun by writing your test functions in parallel with the "production code", since this makes it easy to find bugs and even design flaws earlier. "Support modules" that are not intended to be the main module of a program may include a self-test of the module. :: if __name__ == "__main__": self_test() Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using "fake" interfaces implemented in Python. How do I create documentation from doc strings? ------------------------------------------------------- The `pydoc module `_ can create HTML from the doc strings in your Python source code. An alternative is `pythondoc `_. How do I get a single keypress at a time? ----------------------------------------------- For Unix variants:There are several solutions. It's straightforward to do this using curses, but curses is a fairly large module to learn. Here's a solution without curses:: import termios, fcntl, sys, os fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) try: while 1: try: c = sys.stdin.read(1) print "Got character", `c` except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) You need the ``termios`` and the ``fcntl`` module for any of this to work, and I've only tried it on Linux, though it should work elsewhere. In this code, characters are read and printed one at a time. ``termios.tcsetattr()`` turns off stdin's echoing and disables canonical mode. ``fcntl.fnctl()`` is used to obtain stdin's file descriptor flags and modify them for non-blocking mode. Since reading stdin when it is empty results in an ``IOError``, this error is caught and ignored. Threads ============= How do I program using threads? --------------------------------- Be sure to use `the threading module `_ and not the ``thread`` module. The ``threading`` module builds convenient abstractions on top of the low-level primitives provided by the ``thread`` module. Aahz has a set of slides from his threading tutorial that are helpful; see http://starship.python.net/crew/aahz/OSCON2001/. None of my threads seem to run: why? ------------------------------------------- As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work. A simple fix is to add a sleep to the end of the program that's long enough for all the threads to finish:: import threading, time def thread_task(name, n): for i in range(n): print name, i for i in range(10): T = threading.Thread(target=thread_task, args=(str(i), i)) T.start() time.sleep(10) # <----------------------------! But now (on many platforms) the threads don't run in parallel, but appear to run sequentially, one at a time! The reason is that the OS thread scheduler doesn't start a new thread until the previous thread is blocked. A simple fix is to add a tiny sleep to the start of the run function:: def thread_task(name, n): time.sleep(0.001) # <---------------------! for i in range(n): print name, i for i in range(10): T = threading.Thread(target=thread_task, args=(str(i), i)) T.start() time.sleep(10) Instead of trying to guess how long a ``time.sleep()`` delay will be enough, it's better to use some kind of semaphore mechanism. One idea is to use the `Queue module `_ to create a queue object, let each thread append a token to the queue when it finishes, and let the main thread read as many tokens from the queue as there are threads. How do I parcel out work among a bunch of worker threads? ---------------------------------------------------------------- Use the `Queue module `_ to create a queue containing a list of jobs. The ``Queue`` class maintains a list of objects with ``.put(obj)`` to add an item to the queue and ``.get()`` to return an item. The class will take care of the locking necessary to ensure that each job is handed out exactly once. Here's a trivial example:: import threading, Queue, time # The worker thread gets jobs off the queue. When the queue is empty, it # assumes there will be no more work and exits. # (Realistically workers will run until terminated.) def worker (): print 'Running worker' time.sleep(0.1) while True: try: arg = q.get(block=False) except Queue.Empty: print 'Worker', threading.currentThread(), print 'queue empty' break else: print 'Worker', threading.currentThread(), print 'running with argument', arg time.sleep(0.5) # Create queue q = Queue.Queue() # Start a pool of 5 workers for i in range(5): t = threading.Thread(target=worker, name='worker %i' % (i+1)) t.start() # Begin adding work to the queue for i in range(50): q.put(i) # Give threads time to run print 'Main thread sleeping' time.sleep(5) When run, this will produce the following output: Running worker Running worker Running worker Running worker Running worker Main thread sleeping Worker running with argument 0 Worker running with argument 1 Worker running with argument 2 Worker running with argument 3 Worker running with argument 4 Worker running with argument 5 ... Consult the module's documentation for more details; the ``Queue`` class provides a featureful interface. What kinds of global value mutation are thread-safe? ------------------------------------------------------------ A global interpreter lock (GIL) is used internally to ensure that only one thread runs in the Python VM at a time. In general, Python offers to switch among threads only between bytecode instructions; how frequently it switches can be set via ``sys.setcheckinterval()``. Each bytecode instruction and therefore all the C implementation code reached from each instruction is therefore atomic from the point of view of a Python program. In theory, this means an exact accounting requires an exact understanding of the PVM bytecode implementation. In practice, it means that operations on shared variables of builtin data types (ints, lists, dicts, etc) that "look atomic" really are. For example, the following operations are all atomic (L, L1, L2 are lists, D, D1, D2 are dicts, x, y are objects, i, j are ints):: L.append(x) L1.extend(L2) x = L[i] x = L.pop() L1[i:j] = L2 L.sort() x = y x.field = y D[x] = y D1.update(D2) D.keys() These aren't:: i = i+1 L.append(L[-1]) L[i] = L[j] D[x] = D[x] + 1 Operations that replace other objects may invoke those other objects' ``__del__`` method when their reference count reaches zero, and that can affect things. This is especially true for the mass updates to dictionaries and lists. When in doubt, use a mutex! Can't we get rid of the Global Interpreter Lock? -------------------------------------------------------- The Global Interpreter Lock (GIL) is often seen as a hindrance to Python's deployment on high-end multiprocessor server machines, because a multi-threaded Python program effectively only uses one CPU, due to the insistence that (almost) all Python code can only run while the GIL is held. Back in the days of Python 1.5, Greg Stein actually implemented a comprehensive patch set (the "free threading" patches) that removed the GIL and replaced it with fine-grained locking. Unfortunately, even on Windows (where locks are very efficient) this ran ordinary Python code about twice as slow as the interpreter using the GIL. On Linux the performance loss was even worse because pthread locks aren't as efficient. Since then, the idea of getting rid of the GIL has occasionally come up but nobody has found a way to deal with the expected slowdown, and users who don't use threads would not be happy if their code ran at half at the speed. Greg's free threading patch set has not been kept up-to-date for later Python versions. This doesn't mean that you can't make good use of Python on multi-CPU machines! You just have to be creative with dividing the work up between multiple *processes* rather than multiple *threads*. Judicious use of C extensions will also help; if you use a C extension to perform a time-consuming task, the extension can release the GIL while the thread of execution is in the C code and allow other threads to get some work done. It has been suggested that the GIL should be a per-interpreter-state lock rather than truly global; interpreters then wouldn't be able to share objects. Unfortunately, this isn't likely to happen either. It would be a tremendous amount of work, because many object implementations currently have global state. For example, small integers and short strings are cached; these caches would have to be moved to the interpreter state. Other object types have their own free list; these free lists would have to be moved to the interpreter state. And so on. And I doubt that it can even be done in finite time, because the same problem exists for 3rd party extensions. It is likely that 3rd party extensions are being written at a faster rate than you can convert them to store all their global state in the interpreter state. And finally, once you have multiple interpreters not sharing any state, what have you gained over running each interpreter in a separate process? Input and Output ========================= How do I delete a file? (And other file questions...) --------------------------------------------------------- Use ``os.remove(filename)`` or ``os.unlink(filename)``; for documentation, see `the POSIX module `_. The two functions are identical; ``unlink()`` is simply the name of the Unix system call for this function. To remove a directory, use ``os.rmdir()``; use ``os.mkdir()`` to create one. ``os.makedirs(path)`` will create any intermediate directories in ``path`` that don't exist. ``os.removedirs(path)`` will remove intermediate directories as long as they're empty; if you want to delete an entire directory tree and its contents, use ``shutil.rmtree()``. To rename a file, use ``os.rename(old_path, new_path)``. To truncate a file, open it using ``f = open(filename, "r+")``, and use ``f.truncate(offset)``; offset defaults to the current seek position. There's also ```os.ftruncate(fd, offset)`` for files opened with ``os.open()``, where ``fd`` is the file descriptor (a small integer). The ``shutil`` module also contains a number of functions to work on files including ``copyfile``, ``copytree``, and ``rmtree``. How do I copy a file? ----------------------------- The ``shutil`` module contains a ``copyfile()`` function. Note that on MacOS 9 it doesn't copy the resource fork and Finder info. How do I read (or write) binary data? --------------------------------------------- or complex data formats, it's best to use `the struct module `_. It allows you to take a string containing binary data (usually numbers) and convert it to Python objects; and vice versa. For example, the following code reads two 2-byte integers and one 4-byte integer in big-endian format from a file:: import struct f = open(filename, "rb") # Open in binary mode for portability s = f.read(8) x, y, z = struct.unpack(">hhl", s) The '>' in the format string forces big-endian data; the letter 'h' reads one "short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the string. For data that is more regular (e.g. a homogeneous list of ints or thefloats), you can also use `the array module `_. I can't seem to use os.read() on a pipe created with os.popen(); why? ------------------------------------------------------------------------ ``os.read()`` is a low-level function which takes a file descriptor, a small integer representing the opened file. ``os.popen()`` creates a high-level file object, the same type returned by the builtin ``open()`` function. Thus, to read n bytes from a pipe p created with ``os.popen()``, you need to use ``p.read(n)``. How do I run a subprocess with pipes connected to both input and output? -------------------------------------------------------------------------------- Use `the popen2 module `_. For example:: import popen2 fromchild, tochild = popen2.popen2("command") tochild.write("input\n") tochild.flush() output = fromchild.readline() Warning: in general it is unwise to do this because you can easily cause a deadlock where your process is blocked waiting for output from the child while the child is blocked waiting for input from you. This can be caused because the parent expects the child to output more text than it does, or it can be caused by data being stuck in stdio buffers due to lack of flushing. The Python parent can of course explicitly flush the data it sends to the child before it reads any output, but if the child is a naive C program it may have been written to never explicitly flush its output, even if it is interactive, since flushing is normally automatic. Note that a deadlock is also possible if you use ``popen3`` to read stdout and stderr. If one of the two is too large for the internal buffer (increasing the buffer size does not help) and you ``read()`` the other one first, there is a deadlock, too. Note on a bug in popen2: unless your program calls ``wait()`` or ``waitpid()``, finished child processes are never removed, and eventually calls to popen2 will fail because of a limit on the number of child processes. Calling ``os.waitpid`` with the ``os.WNOHANG`` option can prevent this; a good place to insert such a call would be before calling ``popen2`` again. In many cases, all you really need is to run some data through a command and get the result back. Unless the amount of data is very large, the easiest way to do this is to write it to a temporary file and run the command with that temporary file as input. The `standard module tempfile `_ exports a ``mktemp()`` function to generate unique temporary file names. :: import tempfile import os class Popen3: """ This is a deadlock-safe version of popen that returns an object with errorlevel, out (a string) and err (a string). (capturestderr may not work under windows.) Example: print Popen3('grep spam','\n\nhere spam\n\n').out """ def __init__(self,command,input=None,capturestderr=None): outfile=tempfile.mktemp() command="( %s ) > %s" % (command,outfile) if input: infile=tempfile.mktemp() open(infile,"w").write(input) command=command+" <"+infile if capturestderr: errfile=tempfile.mktemp() command=command+" 2>"+errfile self.errorlevel=os.system(command) >> 8 self.out=open(outfile,"r").read() os.remove(outfile) if input: os.remove(infile) if capturestderr: self.err=open(errfile,"r").read() os.remove(errfile) Note that many interactive programs (e.g. vi) don't work well with pipes substituted for standard input and output. You will have to use pseudo ttys ("ptys") instead of pipes. Or you can use a Python interface to Don Libes' "expect" library. A Python extension that interfaces to expect is called "expy" and available from http://expectpy.sourceforge.net. A pure Python solution that works like expect is ` pexpect `_. How do I access the serial (RS232) port? ------------------------------------------------ For Win32, POSIX (Linux, BSD, etc.), Jython: http://pyserial.sourceforge.net For Unix, see a Usenet post by Mitch Chapman: http://groups.google.com/groups?selm=34A04430.CF9@ohioee.com Why doesn't closing sys.stdout (stdin, stderr) really close it? ----------------------------------------------------------------------- Python file objects are a high-level layer of abstraction on top of C streams, which in turn are a medium-level layer of abstraction on top of (among other things) low-level C file descriptors. For most file objects you create in Python via the builtin ``file`` constructor, ``f.close()`` marks the Python file object as being closed from Python's point of view, and also arranges to close the underlying C stream. This also happens automatically in f's destructor, when f becomes garbage. But stdin, stdout and stderr are treated specially by Python, because of the special status also given to them by C. Running ``sys.stdout.close()`` marks the Python-level file object as being closed, but does *not* close the associated C stream. To close the underlying C stream for one of these three, you should first be sure that's what you really want to do (e.g., you may confuse extension modules trying to do I/O). If it is, use os.close:: os.close(0) # close C's stdin stream os.close(1) # close C's stdout stream os.close(2) # close C's stderr stream Network/Internet Programming ======================================= What WWW tools are there for Python? -------------------------------------------- See the chapters titled `"Internet Protocols and Support" `_ and `"Internet Data Handling" `_ in the Library Reference Manual. Python has many modules that will help you build server-side and client-side web systems. A summary of available frameworks is maintained by Paul Boddie at http://www.python.org/cgi-bin/moinmoin/WebProgramming . Cameron Laird maintains a useful set of pages about Python web technologies at http://phaseit.net/claird/comp.lang.python/web_python.html. The `Web Programming topic guide `_ also points to many useful resources. How can I mimic CGI form submission (METHOD=POST)? ---------------------------------------------------------- I would like to retrieve web pages that are the result of POSTing a form. Is there existing code that would let me do this easily? Yes. Here's a simple example that uses httplib:: #!/usr/local/bin/python import httplib, sys, time ### build the query string qs = "First=Josephine&MI=Q&Last=Public" ### connect and send the server a path httpobj = httplib.HTTP('www.some-server.out-there', 80) httpobj.putrequest('POST', '/cgi-bin/some-cgi-script') ### now generate the rest of the HTTP headers... httpobj.putheader('Accept', '*/*') httpobj.putheader('Connection', 'Keep-Alive') httpobj.putheader('Content-type', 'application/x-www-form-urlencoded') httpobj.putheader('Content-length', '%d' % len(qs)) httpobj.endheaders() httpobj.send(qs) ### find out what the server said in response... reply, msg, hdrs = httpobj.getreply() if reply != 200: sys.stdout.write(httpobj.getfile().read()) Note that in general for URL-encoded POST operations, query strings must be quoted by using ``urllib.quote()``. For example to send name="Guy Steele, Jr.":: >>> from urllib import quote >>> x = quote("Guy Steele, Jr.") >>> x 'Guy%20Steele,%20Jr.' >>> query_string = "name="+x >>> query_string 'name=Guy%20Steele,%20Jr.' What module should I use to help with generating HTML? -------------------------------------------------------------- There are many different modules available: * HTMLgen is a class library of objects corresponding to all the HTML 3.2 markup tags. It's used when you are writing in Python and wish to synthesize HTML pages for generating a web or for CGI forms, etc. * DocumentTemplate and Zope Page Templates are two different systems that are part of Zope. * Quixote's PTL uses Python syntax to assemble strings of text. Consult the `Web Programming topic guide `_ for more links. How do I send mail from a Python script? ------------------------------------------------ Use `the standard library module smtplib `_. Here's a very simple interactive mail sender that uses it. This method will work on any host that supports an SMTP listener. :: import sys, smtplib fromaddr = raw_input("From: ") toaddrs = raw_input("To: ").split(',') print "Enter message, end with ^D:" msg = '' while 1: line = sys.stdin.readline() if not line: break msg = msg + line # The actual mail send server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg) server.quit() A Unix-only alternative uses sendmail. The location of the sendmail program varies between systems; sometimes it is ``/usr/lib/sendmail``, sometime ``/usr/sbin/sendmail``. The sendmail manual page will help you out. Here's some sample code:: SENDMAIL = "/usr/sbin/sendmail" # sendmail location import os p = os.popen("%s -t -i" % SENDMAIL, "w") p.write("To: receiver@example.com\n") p.write("Subject: test\n") p.write("\n") # blank line separating headers from body p.write("Some text\n") p.write("some more text\n") sts = p.close() if sts != 0: print "Sendmail exit status", sts How do I avoid blocking in the connect() method of a socket? -------------------------------------------------------------------------- The select module is commonly used to help with asynchronous I/O on sockets. To prevent the TCP connect from blocking, you can set the socket to non-blocking mode. Then when you do the ``connect()``, you will either connect immediately (unlikely) or get an exception that contains the error number as ``.errno``. ``errno.EINPROGRESS`` indicates that the connection is in progress, but hasn't finished yet. Different OSes will return different values, so you're going to have to check what's returned on your system. You can use the ``connect_ex()`` method to avoid creating an exception. It will just return the errno value. To poll, you can call ``connect_ex()`` again later -- 0 or ``errno.EISCONN`` indicate that you're connected -- or you can pass this socket to select to check if it's writeable. Databases ===================== Are there any interfaces to database packages in Python? ---------------------------------------------------------------- Yes. Python 2.3 includes the ``bsddb`` package which provides an interface to the `BerkeleyDB `_ library. Interfaces to disk-based hashes such as `DBM `_ and `GDBM `_ are also included with standard Python. Support for most relational databases is available. See the `Database Topic Guide `_ for details. How do you implement persistent objects in Python? ------------------------------------------------------------ The `pickle library module `_ solves this in a very general way (though you still can't store things like open files, sockets or windows), and the `shelve library module `_ uses pickle and (g)dbm to create persistent mappings containing arbitrary Python objects. For better performance, you can use `the cPickle module `_. A more awkward way of doing things is to use pickle's little sister, marshal. `The marshal module `_ provides very fast ways to store noncircular basic Python types to files and strings, and back again. Although marshal does not do fancy things like store instances or handle shared references properly, it does run extremely fast. For example loading a half megabyte of data may take less than a third of a second. This often beats doing something more complex and general such as using gdbm with pickle/shelve. Why is cPickle so slow? -------------------------------- The default format used by the pickle module is a slow one that results in readable pickles. Making it the default, but it would break backward compatibility:: largeString = 'z' * (100 * 1024) myPickle = cPickle.dumps(largeString, protocol=1) If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come? -------------------------------------------------------------------------------------------------- Databases opened for write access with the bsddb module (and often by the anydbm module, since it will preferentially use bsddb) must explicitly be closed using the ``.close()`` method of the database. The underlying library caches database contents which need to be converted to on-disk form and written. If you have initialized a new bsddb database but not written anything to it before the program crashes, you will often wind up with a zero-length file and encounter an exception the next time the file is opened. I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data? ------------------------------------------------------------------------------------------------------------------------------------ Don't panic! Your data is probably intact. The most frequent cause for the error is that you tried to open an earlier Berkeley DB file with a later version of the Berkeley DB library. Many Linux systems now have all three versions of Berkeley DB available. If you are migrating from version 1 to a newer version use db_dump185 to dump a plain text version of the database. If you are migrating from version 2 to version 3 use db2_dump to create a plain text version of the database. In either case, use db_load to create a new native database for the latest version installed on your computer. If you have version 3 of Berkeley DB installed, you should be able to use db2_load to create a native version 2 database. You should move away from Berkeley DB version 1 files because the hash file code contains known bugs that can corrupt your data. Mathematics and Numerics ================================ How do I generate random numbers in Python? --------------------------------------------------- The `standard module random `_ implements a random number generator. Usage is simple:: import random random.random() This returns a random floating point number in the range [0, 1). There are also many other specialized generators in this module, such as: * ``randrange(a, b)`` chooses an integer in the range [a, b). * ``uniform(a, b)`` chooses a floating point number in the range [a, b). * ``normalvariate(mean, sdev)`` samples the normal (Gaussian) distribution. Some higher-level functions operate on sequences directly, such as: * ``choice(S)`` chooses random element from a given sequence * ``shuffle(L)`` shuffles a list in-place, i.e. permutes it randomly There's also a ``Random`` class you can instantiate to create independent multiple random number generators. python3-defaults-3.6.7/faq/programming.ht0000664000000000000000000017673113305601050015266 0ustar Title: Python Programming FAQ Content-type: text/x-rst ==================================== Programming FAQ ==================================== :Date: $Date: 2005-12-21 22:00:52 -0700 (Wed, 21 Dec 2005) $ :Version: $Revision: 8721 $ :Web site: http://www.python.org/ .. contents:: .. sectnum:: General Questions =========================== Is there a source code level debugger with breakpoints, single-stepping, etc.? ------------------------------------------------------------------------------- Yes. The pdb module is a simple but adequate console-mode debugger for Python. It is part of the standard Python library, and is `documented in the Library Reference Manual `_. You can also write your own debugger by using the code for pdb as an example. The IDLE interactive development environment, which is part of the standard Python distribution (normally available as Tools/scripts/idle), includes a graphical debugger. There is documentation for the IDLE debugger at http://www.python.org/idle/doc/idle2.html#Debugger PythonWin is a Python IDE that includes a GUI debugger based on pdb. The Pythonwin debugger colors breakpoints and has quite a few cool features such as debugging non-Pythonwin programs. A reference can be found at http://www.python.org/windows/pythonwin/. Recent versions of PythonWin are available as a part of the ActivePython distribution (see http://www.activestate.com/Products/ActivePython/index.html). `Boa Constructor `_ is an IDE and GUI builder that uses wxPython. It offers visual frame creation and manipulation, an object inspector, many views on the source like object browsers, inheritance hierarchies, doc string generated html documentation, an advanced debugger, integrated help, and Zope support. `Eric3 `_ is an IDE built on PyQt and the Scintilla editing component. Pydb is a version of the standard Python debugger pdb, modified for use with DDD (Data Display Debugger), a popular graphical debugger front end. Pydb can be found at http://packages.debian.org/unstable/devel/pydb.html> and DDD can be found at http://www.gnu.org/software/ddd. There are a number of commmercial Python IDEs that include graphical debuggers. They include: * Wing IDE (http://wingide.com) * Komodo IDE (http://www.activestate.com/Products/Komodo) Is there a tool to help find bugs or perform static analysis? ---------------------------------------------------------------------- Yes. PyChecker is a static analysis tool that finds bugs in Python source code and warns about code complexity and style. You can get PyChecker from http://pychecker.sf.net. `Pylint `_ is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug-ins to add a custom feature. In addition to the bug checking that PyChecker performs, Pylint offers some additional features such as checking line length, whether variable names are well-formed according to your coding standard, whether declared interfaces are fully implemented, and more. http://www.logilab.org/projects/pylint/documentation provides a full list of Pylint's features. How can I create a stand-alone binary from a Python script? ------------------------------------------------------------------- You don't need the ability to compile Python to C code if all you want is a stand-alone program that users can download and run without having to install the Python distribution first. There are a number of tools that determine the set of modules required by a program and bind these modules together with a Python binary to produce a single executable. One is to use the freeze tool, which is included in the Python source tree as ``Tools/freeze``. It converts Python byte code to C arrays; a C compiler you can embed all your modules into a new program, which is then linked with the standard Python modules. It works by scanning your source recursively for import statements (in both forms) and looking for the modules in the standard Python path as well as in the source directory (for built-in modules). It then turns the bytecode for modules written in Python into C code (array initializers that can be turned into code objects using the marshal module) and creates a custom-made config file that only contains those built-in modules which are actually used in the program. It then compiles the generated C code and links it with the rest of the Python interpreter to form a self-contained binary which acts exactly like your script. Obviously, freeze requires a C compiler. There are several other utilities which don't. The first is Gordon McMillan's installer at http://www.mcmillan-inc.com/install1.html which works on Windows, Linux and at least some forms of Unix. Another is Thomas Heller's py2exe (Windows only) at http://starship.python.net/crew/theller/py2exe A third is Christian Tismer's `SQFREEZE `_ which appends the byte code to a specially-prepared Python interpreter that can find the byte code in the executable. It's possible that a similar approach will be added to Python 2.4, due out some time in 2004. Other tools include Fredrik Lundh's `Squeeze `_ and Anthony Tuininga's `cx_Freeze `_. Are there coding standards or a style guide for Python programs? ------------------------------------------------------------------------ Yes. The coding style required for standard library modules is documented as `PEP 8 <../../peps/pep-0008.html>`_. My program is too slow. How do I speed it up? ---------------------------------------------------- That's a tough one, in general. There are many tricks to speed up Python code; consider rewriting parts in C as a last resort. In some cases it's possible to automatically translate Python to C or x86 assembly language, meaning that you don't have to modify your code to gain increased speed. `Pyrex `_ can compile a slightly modified version of Python code into a C extension, and can be used on many different platforms. `Psyco `_ is a just-in-time compiler that translates Python code into x86 assembly language. If you can use it, Psyco can provide dramatic speedups for critical functions. The rest of this answer will discuss various tricks for squeezing a bit more speed out of Python code. *Never* apply any optimization tricks unless you know you need them, after profiling has indicated that a particular function is the heavily executed hot spot in the code. Optimizations almost always make the code less clear, and you shouldn't pay the costs of reduced clarity (increased development time, greater likelihood of bugs) unless the resulting performance benefit is worth it. There is a page on the wiki devoted to `performance tips `_. Guido van Rossum has written up an anecdote related to optimization at http://www.python.org/doc/essays/list2str.html. One thing to notice is that function and (especially) method calls are rather expensive; if you have designed a purely OO interface with lots of tiny functions that don't do much more than get or set an instance variable or call another method, you might consider using a more direct way such as directly accessing instance variables. Also see the standard module "profile" (`described in the Library Reference manual `_) which makes it possible to find out where your program is spending most of its time (if you have some patience -- the profiling itself can slow your program down by an order of magnitude). Remember that many standard optimization heuristics you may know from other programming experience may well apply to Python. For example it may be faster to send output to output devices using larger writes rather than smaller ones in order to reduce the overhead of kernel system calls. Thus CGI scripts that write all output in "one shot" may be faster than those that write lots of small pieces of output. Also, be sure to use Python's core features where appropriate. For example, slicing allows programs to chop up lists and other sequence objects in a single tick of the interpreter's mainloop using highly optimized C implementations. Thus to get the same effect as:: L2 = [] for i in range[3]: L2.append(L1[i]) it is much shorter and far faster to use :: L2 = list(L1[:3]) # "list" is redundant if L1 is a list. Note that the functionally-oriented builtins such as ``map()``, ``zip()``, and friends can be a convenient accelerator for loops that perform a single task. For example to pair the elements of two lists together:: >>> zip([1,2,3], [4,5,6]) [(1, 4), (2, 5), (3, 6)] or to compute a number of sines:: >>> map( math.sin, (1,2,3,4)) [0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308] The operation completes very quickly in such cases. Other examples include the ``join()`` and ``split()`` methods of string objects. For example if s1..s7 are large (10K+) strings then ``"".join([s1,s2,s3,s4,s5,s6,s7])` may be far faster than the more obvious ``s1+s2+s3+s4+s5+s6+s7``, since the "summation" will compute many subexpressions, whereas ``join()`` does all the copying in one pass. For manipulating strings, use the ``replace()`` method on string objects. Use regular expressions only when you're not dealing with constant string patterns. Consider using the string formatting operations ``string % tuple`` and ``string % dictionary``. Be sure to use the ``list.sort()`` builtin method to do sorting, and see the `sorting mini-HOWTO `_ for examples of moderately advanced usage. ``list.sort()`` beats other techniques for sorting in all but the most extreme circumstances. Another common trick is to "push loops into functions or methods." For example suppose you have a program that runs slowly and you use the profiler to determine that a Python function ``ff()`` is being called lots of times. If you notice that ``ff ()``:: def ff(x): ...do something with x computing result... return result tends to be called in loops like:: list = map(ff, oldlist) or:: for x in sequence: value = ff(x) ...do something with value... then you can often eliminate function call overhead by rewriting ``ff()`` to:: def ffseq(seq): resultseq = [] for x in seq: ...do something with x computing result... resultseq.append(result) return resultseq and rewrite the two examples to ``list = ffseq(oldlist)`` and to:: for value in ffseq(sequence): ...do something with value... Single calls to ff(x) translate to ffseq([x])[0] with little penalty. Of course this technique is not always appropriate and there are other variants which you can figure out. You can gain some performance by explicitly storing the results of a function or method lookup into a local variable. A loop like:: for key in token: dict[key] = dict.get(key, 0) + 1 resolves dict.get every iteration. If the method isn't going to change, a slightly faster implementation is:: dict_get = dict.get # look up the method once for key in token: dict[key] = dict_get(key, 0) + 1 Default arguments can be used to determine values once, at compile time instead of at run time. This can only be done for functions or objects which will not be changed during program execution, such as replacing :: def degree_sin(deg): return math.sin(deg * math.pi / 180.0) with :: def degree_sin(deg, factor = math.pi/180.0, sin = math.sin): return sin(deg * factor) Because this trick uses default arguments for terms which should not be changed, it should only be used when you are not concerned with presenting a possibly confusing API to your users. Core Language ================== How do you set a global variable in a function? ---------------------------------------------------------- Did you do something like this? :: x = 1 # make a global def f(): print x # try to print the global ... for j in range(100): if q>3: x=4 Any variable assigned in a function is local to that function. unless it is specifically declared global. Since a value is bound to ``x`` as the last statement of the function body, the compiler assumes that ``x`` is local. Consequently the ``print x`` attempts to print an uninitialized local variable and will trigger a ``NameError``. The solution is to insert an explicit global declaration at the start of the function:: def f(): global x print x # try to print the global ... for j in range(100): if q>3: x=4 In this case, all references to ``x`` are interpreted as references to the ``x`` from the module namespace. What are the rules for local and global variables in Python? -------------------------------------------------------------------------- In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'. Though a bit surprising at first, a moment's consideration explains this. On one hand, requiring ``global`` for assigned variables provides a bar against unintended side-effects. On the other hand, if ``global`` was required for all global references, you'd be using ``global`` all the time. You'd have to declare as global every reference to a builtin function or to a component of an imported module. This clutter would defeat the usefulness of the ``global`` declaration for identifying side-effects. How do I share global variables across modules? ------------------------------------------------ The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example: config.py:: x = 0 # Default value of the 'x' configuration setting mod.py:: import config config.x = 1 main.py:: import config import mod print config.x Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason. What are the "best practices" for using import in a module? ------------------------------------------------------------------------------ In general, don't use ``from modulename import *``. Doing so clutters the importer's namespace. Some people avoid this idiom even with the few modules that were designed to be imported in this manner. Modules designed in this manner include ``Tkinter``, and ``threading``. Import modules at the top of a file. Doing so makes it clear what other modules your code requires and avoids questions of whether the module name is in scope. Using one import per line makes it easy to add and delete module imports, but using multiple imports per line uses less screen space. It's good practice if you import modules in the following order: 1. standard libary modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``) 2. third-party library modules (anything installed in Python's site-packages directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc. 3. locally-developed modules Never use relative package imports. If you're writing code that's in the ``package.sub.m1`` module and want to import ``package.sub.m2``, do not just write ``import m2``, even though it's legal. Write ``from package.sub import m2`` instead. Relative imports can lead to a module being initialized twice, leading to confusing bugs. It is sometimes necessary to move imports to a function or class to avoid problems with circular imports. Gordon McMillan says: Circular imports are fine where both modules use the "import " form of import. They fail when the 2nd module wants to grab a name out of the first ("from module import name") and the import is at the top level. That's because names in the 1st are not yet available, because the first module is busy importing the 2nd. In this case, if the second module is only used in one function, then the import can easily be moved into that function. By the time the import is called, the first module will have finished initializing, and the second module can do its import. It may also be necessary to move imports out of the top level of code if some of the modules are platform-specific. In that case, it may not even be possible to import all of the modules at the top of the file. In this case, importing the correct modules in the corresponding platform-specific code is a good option. Only move imports into a local scope, such as inside a function definition, if it's necessary to solve a problem such as avoiding a circular import or are trying to reduce the initialization time of a module. This technique is especially helpful if many of the imports are unnecessary depending on how the program executes. You may also want to move imports into a function if the modules are only ever used in that function. Note that loading a module the first time may be expensive because of the one time initialization of the module, but loading a module multiple times is virtually free, costing only a couple of dictionary lookups. Even if the module name has gone out of scope, the module is probably available in sys.modules. If only instances of a specific class use a module, then it is reasonable to import the module in the class's ``__init__`` method and then assign the module to an instance variable so that the module is always available (via that instance variable) during the life of the object. Note that to delay an import until the class is instantiated, the import must be inside a method. Putting the import inside the class but outside of any method still causes the import to occur when the module is initialized. How can I pass optional or keyword parameters from one function to another? ------------------------------------------------------------------------------- Collect the arguments using the ``*`` and ``**`` specifiers in the function's parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using ``*`` and ``**``:: def f(x, *tup, **kwargs): ... kwargs['width']='14.3c' ... g(x, *tup, **kwargs) In the unlikely case that you care about Python versions older than 2.0, use 'apply':: def f(x, *tup, **kwargs): ... kwargs['width']='14.3c' ... apply(g, (x,)+tup, kwargs) How do I write a function with output parameters (call by reference)? ----------------------------------------------------------------------------- Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there's no alias between an argument name in the caller and callee, and so no call-by-reference per se. You can achieve the desired effect in a number of ways. 1) By returning a tuple of the results:: def func2(a, b): a = 'new-value' # a and b are local names b = b + 1 # assigned to new objects return a, b # return new values x, y = 'old-value', 99 x, y = func2(x, y) print x, y # output: new-value 100 This is almost always the clearest solution. 2) By using global variables. This isn't thread-safe, and is not recommended. 3) By passing a mutable (changeable in-place) object:: def func1(a): a[0] = 'new-value' # 'a' references a mutable list a[1] = a[1] + 1 # changes a shared object args = ['old-value', 99] func1(args) print args[0], args[1] # output: new-value 100 4) By passing in a dictionary that gets mutated:: def func3(args): args['a'] = 'new-value' # args is a mutable dictionary args['b'] = args['b'] + 1 # change it in-place args = {'a':' old-value', 'b': 99} func3(args) print args['a'], args['b'] 5) Or bundle up values in a class instance:: class callByRef: def __init__(self, **args): for (key, value) in args.items(): setattr(self, key, value) def func4(args): args.a = 'new-value' # args is a mutable callByRef args.b = args.b + 1 # change object in-place args = callByRef(a='old-value', b=99) func4(args) print args.a, args.b There's almost never a good reason to get this complicated. Your best choice is to return a tuple containing the multiple results. How do you make a higher order function in Python? ---------------------------------------------------------- You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define ``linear(a,b)`` which returns a function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes:: def linear(a,b): def result(x): return a*x + b return result Or using a callable object:: class linear: def __init__(self, a, b): self.a, self.b = a,b def __call__(self, x): return self.a * x + self.b In both cases:: taxes = linear(0.3,2) gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2. The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:: class exponential(linear): # __init__ inherited def __call__(self, x): return self.a * (x ** self.b) Object can encapsulate state for several methods:: class counter: value = 0 def set(self, x): self.value = x def up(self): self.value=self.value+1 def down(self): self.value=self.value-1 count = counter() inc, dec, reset = count.up, count.down, count.set Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the same counting variable. How do I copy an object in Python? ------------------------------------------ In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can. Some objects can be copied more easily. Dictionaries have a ``copy()`` method:: newdict = olddict.copy() Sequences can be copied by slicing:: new_l = l[:] How can I find the methods or attributes of an object? -------------------------------------------------------------- For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class. How can my code discover the name of an object? ------------------------------------------------------- Generally speaking, it can't, because objects don't really have names. Essentially, assignment always binds a name to a value; The same is true of ``def`` and ``class`` statements, but in that case the value is a callable. Consider the following code:: class A: pass B = A a = B() b = a print b <__main__.A instance at 016D07CC> print a <__main__.A instance at 016D07CC> Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance's name is a or b, since both names are bound to the same value. Generally speaking it should not be necessary for your code to "know the names" of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial. In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question: The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object)... ....and don't be surprised if you'll find that it's known by many names, or no name at all! Is there an equivalent of C's "?:" ternary operator? ---------------------------------------------------------------------- No. In many cases you can mimic a?b:c with "a and b or c", but there's a flaw: if b is zero (or empty, or None -- anything that tests false) then c will be selected instead. In many cases you can prove by looking at the code that this can't happen (e.g. because b is a constant or has a type that can never be false), but in general this can be a problem. Tim Peters (who wishes it was Steve Majewski) suggested the following solution: (a and [b] or [c])[0]. Because [b] is a singleton list it is never false, so the wrong path is never taken; then applying [0] to the whole thing gets the b or c that you really wanted. Ugly, but it gets you there in the rare cases where it is really inconvenient to rewrite your code using 'if'. The best course is usually to write a simple ``if...else`` statement. Another solution is to implement the "?:" operator as a function:: def q(cond,on_true,on_false): if cond: if not isfunction(on_true): return on_true else: return apply(on_true) else: if not isfunction(on_false): return on_false else: return apply(on_false) In most cases you'll pass b and c directly: ``q(a,b,c)``. To avoid evaluating b or c when they shouldn't be, encapsulate them within a lambda function, e.g.: ``q(a,lambda: b, lambda: c)``. It has been asked *why* Python has no if-then-else expression. There are several answers: many languages do just fine without one; it can easily lead to less readable code; no sufficiently "Pythonic" syntax has been discovered; a search of the standard library found remarkably few places where using an if-then-else expression would make the code more understandable. In 2002, `PEP 308 <../../peps/pep-0308.html>`_ was written proposing several possible syntaxes and the community was asked to vote on the issue. The vote was inconclusive. Most people liked one of the syntaxes, but also hated other syntaxes; many votes implied that people preferred no ternary operator rather than having a syntax they hated. Is it possible to write obfuscated one-liners in Python? ---------------------------------------------------------------- Yes. Usually this is done by nesting `lambda` within `lambda`. See the following three examples, due to Ulf Bartelt:: # Primes < 1000 print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0, map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000))) # First 10 Fibonacci numbers print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f), range(10)) # Mandelbrot set print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y, Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM, Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro, i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr( 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24) # \___ ___ \___ ___ | | |__ lines on screen # V V | |______ columns on screen # | | |__________ maximum of "iterations" # | |_________________ range on y axis # |____________________________ range on x axis Don't try this at home, kids! Numbers and strings ========================== How do I specify hexadecimal and octal integers? -------------------------------------------------------- To specify an octal digit, precede the octal value with a zero. For example, to set the variable "a" to the octal value "10" (8 in decimal), type:: >>> a = 010 >>> a 8 Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero, and then a lower or uppercase "x". Hexadecimal digits can be specified in lower or uppercase. For example, in the Python interpreter:: >>> a = 0xa5 >>> a 165 >>> b = 0XB2 >>> b 178 Why does -22 / 10 return -3? ---------------------------------- It's primarily driven by the desire that ``i%j`` have the same sign as ``j``. If you want that, and also want:: i == (i/j)*j + (i%j) then integer division has to return the floor. C also requres that identity to hold, and then compilers that truncate ``i/j`` need to make ``i%j`` have the same sign as ``i``. There are few real use cases for ``i%j`` when ``j`` is negative. When ``j`` is positive, there are many, and in virtually all of them it's more useful for ``i%j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to bite. How do I convert a string to a number? ---------------------------------------------- For integers, use the built-in ``int()`` type constructor, e.g. int('144') == 144. Similarly, ``float()`` converts to floating-point, e.g. ``float('144') == 144.0``. By default, these interpret the number as decimal, so that ``int('0144') == 144`` and ``int('0x144')`` raises ``ValueError``. ``int(string, base)`` takes the base to convert from as a second optional argument, so ``int('0x144', 16) == 324``. If the base is specified as 0, the number is interpreted using Python's rules: a leading '0' indicates octal, and '0x' indicates a hex number. Do not use the built-in function ``eval()`` if all you need is to convert strings to numbers. ``eval()`` will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass ``__import__('os').system("rm -rf $HOME")`` which would erase your home directory. ``eval()`` also has the effect of interpreting numbers as Python expressions, so that e.g. eval('09') gives a syntax error because Python regards numbers starting with '0' as octal (base 8). How do I convert a number to a string? ---------------------------------------------- To convert, e.g., the number 144 to the string '144', use the built-in function ``str()``. If you want a hexadecimal or octal representation, use the built-in functions ``hex()`` or ``oct()``. For fancy formatting, use `the % operator <../../doc/lib/typesseq-strings.html>`_ on strings, e.g. ``"%04d" % 144`` yields '0144' and ``"%.3f" % (1/3.0)`` yields '0.333'. See the library reference manual for details. How do I modify a string in place? ------------------------------------------ You can't, because strings are immutable. If you need an object with this ability, try converting the string to a list or use the array module:: >>> s = "Hello, world" >>> a = list(s) >>> print a ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd'] >>> a[7:] = list("there!") >>> ''.join(a) 'Hello, there!' >>> import array >>> a = array.array('c', s) >>> print a array('c', 'Hello, world') >>> a[0] = 'y' ; print a array('c', 'yello world') >>> a.tostring() 'yello, world' How do I use strings to call functions/methods? ---------------------------------------------------------- There are various techniques. * The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct:: def a(): pass def b(): pass dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs dispatch[get_input()]() # Note trailing parens to call function * Use the built-in function ``getattr()``:: import foo getattr(foo, 'bar')() Note that getattr() works on any object, including classes, class instances, modules, and so on. This is used in several places in the standard library, like this:: class Foo: def do_foo(self): ... def do_bar(self): ... f = getattr(foo_instance, 'do_' + opname) f() * Use ``locals()`` or ``eval()`` to resolve the function name:: def myFunc(): print "hello" fname = "myFunc" f = locals()[fname] f() f = eval(fname) f() Note: Using ``eval()`` is slow and dangerous. If you don't have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being executed. Is there an equivalent to Perl's chomp() for removing trailing newlines from strings? -------------------------------------------------------------------------------------------- Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove all occurances of any line terminator from the end of the string ``S`` without removing other trailing whitespace. If the string ``S`` represents more than one line, with several empty lines at the end, the line terminators for all the blank lines will be removed:: >>> lines = ("line 1 \r\n" ... "\r\n" ... "\r\n") >>> lines.rstrip("\n\r") "line 1 " Since this is typically only desired when reading text one line at a time, using ``S.rstrip()`` this way works well. For older versions of Python, There are two partial substitutes: - If you want to remove all trailing whitespace, use the ``rstrip()`` method of string objects. This removes all trailing whitespace, not just a single newline. - Otherwise, if there is only one line in the string ``S``, use ``S.splitlines()[0]``. Is there a scanf() or sscanf() equivalent? -------------------------------------------------- Not as such. For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the ``split()`` method of string objects and then convert decimal strings to numeric values using ``int()`` or ``float()``. ``split()`` supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator. For more complicated input parsing, regular expressions more powerful than C's ``sscanf()`` and better suited for the task. What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean? ----------------------------------------------------------------------------------------------------- This error indicates that your Python installation can handle only 7-bit ASCII strings. There are a couple ways to fix or work around the problem. If your programs must handle data in arbitary character set encodings, the environment the application runs in will generally identify the encoding of the data it is handing you. You need to convert the input to Unicode data using that encoding. For example, a program that handles email or web input will typically find character set encoding information in Content-Type headers. This can then be used to properly convert input data to Unicode. Assuming the string referred to by ``value`` is encoded as UTF-8:: value = unicode(value, "utf-8") will return a Unicode object. If the data is not correctly encoded as UTF-8, the above call will raise a ``UnicodeError`` exception. If you only want strings coverted to Unicode which have non-ASCII data, you can try converting them first assuming an ASCII encoding, and then generate Unicode objects if that fails:: try: x = unicode(value, "ascii") except UnicodeError: value = unicode(value, "utf-8") else: # value was valid ASCII data pass It's possible to set a default encoding in a file called ``sitecustomize.py`` that's part of the Python library. However, this isn't recommended because changing the Python-wide default encoding may cause third-party extension modules to fail. Note that on Windows, there is an encoding known as "mbcs", which uses an encoding specific to your current locale. In many cases, and particularly when working with COM, this may be an appropriate default encoding to use. Sequences (Tuples/Lists) ================================= How do I convert between tuples and lists? ------------------------------------------------ The function ``tuple(seq)`` converts any sequence (actually, any iterable) into a tuple with the same items in the same order. For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')`` yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy but returns the same object, so it is cheap to call ``tuple()`` when you aren't sure that an object is already a tuple. The function ``list(seq)`` converts any sequence or iterable into a list with the same items in the same order. For example, ``list((1, 2, 3))`` yields ``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument is a list, it makes a copy just like ``seq[:]`` would. What's a negative index? -------------------------------------------------------------------- Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the pentultimate (next to last) index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``. Using negative indices can be very convenient. For example ``S[:-1]`` is all of the string except for its last character, which is useful for removing the trailing newline from a string. How do I iterate over a sequence in reverse order? --------------------------------------------------------- If it is a list, the fastest solution is :: list.reverse() try: for x in list: "do something with x" finally: list.reverse() This has the disadvantage that while you are in the loop, the list is temporarily reversed. If you don't like this, you can make a copy. This appears expensive but is actually faster than other solutions:: rev = list[:] rev.reverse() for x in rev: If it's not a list, a more general but slower solution is:: for i in range(len(sequence)-1, -1, -1): x = sequence[i] A more elegant solution, is to define a class which acts as a sequence and yields the elements in reverse order (solution due to Steve Majewski):: class Rev: def __init__(self, seq): self.forw = seq def __len__(self): return len(self.forw) def __getitem__(self, i): return self.forw[-(i + 1)] You can now simply write:: for x in Rev(list): Unfortunately, this solution is slowest of all, due to the method call overhead. With Python 2.3, you can use an extended slice syntax:: for x in sequence[::-1]: How do you remove duplicates from a list? ------------------------------------------------- See the Python Cookbook for a long discussion of many ways to do this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 If you don't mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as you go:: if List: List.sort() last = List[-1] for i in range(len(List)-2, -1, -1): if last==List[i]: del List[i] else: last=List[i] If all elements of the list may be used as dictionary keys (i.e. they are all hashable) this is often faster :: d = {} for x in List: d[x]=x List = d.values() How do you make an array in Python? ---------------------------------------------------- Use a list:: ["this", 1, "is", "an", "array"] Lists are equivalent to C or Pascal arrays in their time complexity; the primary difference is that a Python list can contain objects of many different types. The ``array`` module also provides methods for creating arrays of fixed types with compact representations, but they are slower to index than lists. Also note that the Numeric extensions and others define array-like structures with various characteristics as well. To get Lisp-style linked lists, you can emulate cons cells using tuples:: lisp_list = ("like", ("this", ("example", None) ) ) If mutability is desired, you could use lists instead of tuples. Here the analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is ``lisp_list[1]``. Only do this if you're sure you really need to, because it's usually a lot slower than using Python lists. How do I create a multidimensional list? --------------------------------------------------------------- You probably tried to make a multidimensional array like this:: A = [[None] * 2] * 3 This looks correct if you print it:: >>> A [[None, None], [None, None], [None, None]] But when you assign a value, it shows up in multiple places: >>> A[0][0] = 5 >>> A [[5, None], [5, None], [5, None]] The reason is that replicating a list with ``*`` doesn't create copies, it only creates references to the existing objects. The ``*3`` creates a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is almost certainly not what you want. The suggested approach is to create a list of the desired length first and then fill in each element with a newly created list:: A = [None]*3 for i in range(3): A[i] = [None] * 2 This generates a list containing 3 different lists of length two. You can also use a list comprehension:: w,h = 2,3 A = [ [None]*w for i in range(h) ] Or, you can use an extension that provides a matrix datatype; `Numeric Python `_ is the best known. How do I apply a method to a sequence of objects? -------------------------------------------------------------------------- Use a list comprehension:: result = [obj.method() for obj in List] More generically, you can try the following function:: def method_map(objects, method, arguments): """method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]""" nobjects = len(objects) methods = map(getattr, objects, [method]*nobjects) return map(apply, methods, [arguments]*nobjects) Dictionaries ================== How can I get a dictionary to display its keys in a consistent order? ----------------------------------------------------------------------------- You can't. Dictionaries store their keys in an unpredictable order, so the display order of a dictionary's elements will be similarly unpredictable. This can be frustrating if you want to save a printable version to a file, make some changes and then compare it with some other printed dictionary. In this case, use the ``pprint`` module to pretty-print the dictionary; the items will be presented in order sorted by the key. A more complicated solution is to subclass ``UserDict.UserDict`` to create a ``SortedDict`` class that prints itself in a predictable order. Here's one simpleminded implementation of such a class:: import UserDict, string class SortedDict(UserDict.UserDict): def __repr__(self): result = [] append = result.append keys = self.data.keys() keys.sort() for k in keys: append("%s: %s" % (`k`, `self.data[k]`)) return "{%s}" % string.join(result, ", ") ___str__ = __repr__ This will work for many common situations you might encounter, though it's far from a perfect solution. The largest flaw is that if some values in the dictionary are also dictionaries, their values won't be presented in any particular order. I want to do a complicated sort: can you do a Schwartzian Transform in Python? -------------------------------------------------------------------------------------- Yes, it's quite simple with list comprehensions. The technique, attributed to Randal Schwartz of the Perl community, sorts the elements of a list by a metric which maps each element to its "sort value". To sort a list of strings by their uppercase values:: tmp1 = [ (x.upper(), x) for x in L ] # Schwartzian transform tmp1.sort() Usorted = [ x[1] for x in tmp1 ] To sort by the integer value of a subfield extending from positions 10-15 in each string:: tmp2 = [ (int(s[10:15]), s) for s in L ] # Schwartzian transform tmp2.sort() Isorted = [ x[1] for x in tmp2 ] Note that Isorted may also be computed by :: def intfield(s): return int(s[10:15]) def Icmp(s1, s2): return cmp(intfield(s1), intfield(s2)) Isorted = L[:] Isorted.sort(Icmp) but since this method calls ``intfield()`` many times for each element of L, it is slower than the Schwartzian Transform. How can I sort one list by values from another list? ------------------------------------------------------------ Merge them into a single list of tuples, sort the resulting list, and then pick out the element you want. :: >>> list1 = ["what", "I'm", "sorting", "by"] >>> list2 = ["something", "else", "to", "sort"] >>> pairs = zip(list1, list2) >>> pairs [('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')] >>> pairs.sort() >>> result = [ x[1] for x in pairs ] >>> result ['else', 'sort', 'to', 'something'] An alternative for the last step is:: result = [] for p in pairs: result.append(p[1]) If you find this more legible, you might prefer to use this instead of the final list comprehension. However, it is almost twice as slow for long lists. Why? First, the ``append()`` operation has to reallocate memory, and while it uses some tricks to avoid doing that each time, it still has to do it occasionally, and that costs quite a bit. Second, the expression "result.append" requires an extra attribute lookup, and third, there's a speed reduction from having to make all those function calls. Objects ============= What is a class? ------------------------ A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a datatype. A class can be based on one or more other classes, called its base class(es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined by inheritance. You might have a generic ``Mailbox`` class that provides basic accessor methods for a mailbox, and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox`` that handle various specific mailbox formats. What is a method? ------------------------- A method is a function on some object ``x`` that you normally call as ``x.name(arguments...)``. Methods are defined as functions inside the class definition:: class C: def meth (self, arg): return arg*2 + self.attribute What is self? --------------------- Self is merely a conventional name for the first argument of a method. A method defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for some instance ``x`` of the class in which the definition occurs; the called method will think it is called as ``meth(x, a, b, c)``. See also `Why must 'self' be used explicitly in method definitions and calls? `_ How do I check if an object is an instance of a given class or of a subclass of it? ------------------------------------------------------------------------------------------- Use the built-in function ``isinstance(obj, cls)``. You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also check whether an object is one of Python's built-in types, e.g. ``isinstance(obj, str)`` or ``isinstance(obj, (int, long, float, complex))``. Note that most programs do not use ``isinstance()`` on user-defined classes very often. If you are developing the classes yourself, a more proper object-oriented style is to define methods on the classes that encapsulate a particular behaviour, instead of checking the object's class and doing a different thing based on what class it is. For example, if you have a function that does something:: def search (obj): if isinstance(obj, Mailbox): # ... code to search a mailbox elif isinstance(obj, Document): # ... code to search a document elif ... A better approach is to define a ``search()`` method on all the classes and just call it:: class Mailbox: def search(self): # ... code to search a mailbox class Document: def search(self): # ... code to search a document obj.search() What is delegation? --------------------------- Delegation is an object oriented technique (also called a design pattern). Let's say you have an object ``x`` and want to change the behaviour of just one of its methods. You can create a new class that provides a new implementation of the method you're interested in changing and delegates all other methods to the corresponding method of ``x``. Python programmers can easily implement delegation. For example, the following class implements a class that behaves like a file but converts all written data to uppercase:: class UpperOut: def __init__(self, outfile): self.__outfile = outfile def write(self, s): self.__outfile.write(s.upper()) def __getattr__(self, name): return getattr(self.__outfile, name) Here the ``UpperOut`` class redefines the ``write()`` method to convert the argument string to uppercase before calling the underlying ``self.__outfile.write()`` method. All other methods are delegated to the underlying ``self.__outfile`` object. The delegation is accomplished via the ``__getattr__`` method; consult `the language reference <../../doc/ref/attribute-access.html>`_ for more information about controlling attribute access. Note that for more general cases delegation can get trickier. When attributes must be set as well as retrieved, the class must define a ``__settattr__`` method too, and it must do so carefully. The basic implementation of __setattr__ is roughly equivalent to the following:: class X: ... def __setattr__(self, name, value): self.__dict__[name] = value ... Most __setattr__ implementations must modify self.__dict__ to store local state for self without causing an infinite recursion. How do I call a method defined in a base class from a derived class that overrides it? ---------------------------------------------------------------------------------------------- If you're using new-style classes, use the built-in ``super()`` function:: class Derived(Base): def meth (self): super(Derived, self).meth() If you're using classic classes: For a class definition such as ``class Derived(Base): ...`` you can call method ``meth()`` defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self, arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to provide the ``self`` argument. How can I organize my code to make it easier to change the base class? ------------------------------------------------------------------------------ You could define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. Then all you have to change is the value assigned to the alias. Incidentally, this trick is also handy if you want to decide dynamically (e.g. depending on availability of resources) which base class to use. Example:: BaseAlias = class Derived(BaseAlias): def meth(self): BaseAlias.meth(self) ... How do I create static class data and static class methods? ------------------------------------------------------------------- Static data (in the sense of C++ or Java) is easy; static methods (again in the sense of C++ or Java) are not supported directly. For static data, simply define a class attribute. To assign a new value to the attribute, you have to explicitly use the class name in the assignment:: class C: count = 0 # number of times C.__init__ called def __init__(self): C.count = C.count + 1 def getcount(self): return C.count # or return self.count ``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c, C)`` holds, unless overridden by ``c`` itself or by some class on the base-class search path from ``c.__class__`` back to ``C``. Caution: within a method of C, an assignment like ``self.count = 42`` creates a new and unrelated instance vrbl named "count" in ``self``'s own dict. Rebinding of a class-static data name must always specify the class whether inside a method or not:: C.count = 314 Static methods are possible when you're using new-style classes:: class C: def static(arg1, arg2, arg3): # No 'self' parameter! ... static = staticmethod(static) However, a far more straightforward way to get the effect of a static method is via a simple module-level function:: def getcount(): return C.count If your code is structured so as to define one class (or tightly related class hierarchy) per module, this supplies the desired encapsulation. How can I overload constructors (or methods) in Python? --------------------------------------------------------------- This answer actually applies to all methods, but the question usually comes up first in the context of constructors. In C++ you'd write :: class C { C() { cout << "No arguments\n"; } C(int i) { cout << "Argument is " << i << "\n"; } } in Python you have to write a single constructor that catches all cases using default arguments. For example:: class C: def __init__(self, i=None): if i is None: print "No arguments" else: print "Argument is", i This is not entirely equivalent, but close enough in practice. You could also try a variable-length argument list, e.g. :: def __init__(self, *args): .... The same approach works for all method definitions. I try to use __spam and I get an error about _SomeClassName__spam. -------------------------------------------------------------------------- Variables with double leading underscore are "mangled" to provide a simple but effective way to define class private variables. Any identifier of the form ``__spam`` (at least two leading underscores, at most one trailing underscore) is textually replaced with ``_classname__spam``, where ``classname`` is the current class name with any leading underscores stripped. This doesn't guarantee privacy: an outside user can still deliberately access the "_classname__spam" attribute, and private values are visible in the object's ``__dict__``. Many Python programmers never bother to use private variable names at all. My class defines __del__ but it is not called when I delete the object. ------------------------------------------------------------------------------- There are several possible reasons for this. The del statement does not necessarily call __del__ -- it simply decrements the object's reference count, and if this reaches zero __del__ is called. If your data structures contain circular links (e.g. a tree where each child has a parent reference and each parent has a list of children) the reference counts will never go back to zero. Once in a while Python runs an algorithm to detect such cycles, but the garbage collector might run some time after the last reference to your data structure vanishes, so your __del__ method may be called at an inconvenient and random time. This is inconvenient if you're trying to reproduce a problem. Worse, the order in which object's __del__ methods are executed is arbitrary. You can run ``gc.collect()`` to force a collection, but there *are* pathological cases where objects will never be collected. Despite the cycle collector, it's still a good idea to define an explicit ``close()`` method on objects to be called whenever you're done with them. The ``close()`` method can then remove attributes that refer to subobjecs. Don't call ``__del__`` directly -- ``__del__`` should call ``close()`` and ``close()`` should make sure that it can be called more than once for the same object. Another way to avoid cyclical references is to use the "weakref" module, which allows you to point to objects without incrementing their reference count. Tree data structures, for instance, should use weak references for their parent and sibling references (if they need them!). If the object has ever been a local variable in a function that caught an expression in an except clause, chances are that a reference to the object still exists in that function's stack frame as contained in the stack trace. Normally, calling ``sys.exc_clear()`` will take care of this by clearing the last recorded exception. Finally, if your __del__ method raises an exception, a warning message is printed to sys.stderr. How do I get a list of all instances of a given class? -------------------------------------------------------------- Python does not keep track of all instances of a class (or of a built-in type). You can program the class's constructor to keep track of all instances by keeping a list of weak references to each instance. Modules ============= How do I create a .pyc file? ------------------------------------- When a module is imported for the first time (or when the source is more recent than the current compiled file) a ``.pyc`` file containing the compiled code should be created in the same directory as the ``.py`` file. One reason that a ``.pyc`` file may not be created is permissions problems with the directory. This can happen, for example, if you develop as one user but run as another, such as if you are testing with a web server. Creation of a .pyc file is automatic if you're importing a module and Python has the ability (permissions, free space, etc...) to write the compiled module back to the directory. Running Python on a top level script is not considered an import and no ``.pyc`` will be created. For example, if you have a top-level module ``abc.py`` that imports another module ``xyz.py``, when you run abc, ``xyz.pyc`` will be created since xyz is imported, but no ``abc.pyc`` file will be created since ``abc.py`` isn't being imported. If you need to create abc.pyc -- that is, to create a .pyc file for a module that is not imported -- you can, using the py_compile and compileall modules. The ``py_compile`` module can manually compile any module. One way is to use the ``compile()`` function in that module interactively:: >>> import py_compile >>> py_compile.compile('abc.py') This will write the ``.pyc`` to the same location as ``abc.py`` (or you can override that with the optional parameter ``cfile``). You can also automatically compile all files in a directory or directories using the ``compileall`` module. You can do it from the shell prompt by running ``compileall.py`` and providing the path of a directory containing Python files to compile:: python compileall.py . How do I find the current module name? --------------------------------------------- A module can find out its own module name by looking at the predefined global variable ``__name__``. If this has the value '__main__', the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking ``__name__``:: def main(): print 'Running test...' ... if __name__ == '__main__': main() How can I have modules that mutually import each other? --------------------------------------------------------------- Suppose you have the following modules: foo.py:: from bar import bar_var foo_var=1 bar.py:: from foo import foo_var bar_var=2 The problem is that the interpreter will perform the following steps: * main imports foo * Empty globals for foo are created * foo is compiled and starts executing * foo imports bar * Empty globals for bar are created * bar is compiled and starts executing * bar imports foo (which is a no-op since there already is a module named foo) * bar.foo_var = foo.foo_var The last step fails, because Python isn't done with interpreting ``foo`` yet and the global symbol dictionary for ``foo`` is still empty. The same thing happens when you use ``import foo``, and then try to access ``foo.foo_var`` in global code. There are (at least) three possible workarounds for this problem. Guido van Rossum recommends avoiding all uses of ``from import ...``, and placing all code inside functions. Initializations of global variables and class variables should use constants or built-in functions only. This means everything from an imported module is referenced as ``.``. Jim Roskind suggests performing steps in the following order in each module: * exports (globals, functions, and classes that don't need imported base classes) * ``import`` statements * active code (including globals that are initialized from imported values). van Rossum doesn't like this approach much because the imports appear in a strange place, but it does work. Matthias Urlichs recommends restructuring your code so that the recursive import is not necessary in the first place. These solutions are not mutually exclusive. __import__('x.y.z') returns ; how do I get z? ----------------------------------------------------------------------- Try:: __import__('x.y.z').y.z For more realistic situations, you may have to do something like :: m = __import__(s) for i in s.split(".")[1:]: m = getattr(m, i) When I edit an imported module and reimport it, the changes don't show up. Why does this happen? -------------------------------------------------------------------------------------------------------------------------------------------- For reasons of efficiency as well as consistency, Python only reads the module file on the first time a module is imported. If it didn't, in a program consisting of many modules where each one imports the same basic module, the basic module would be parsed and re-parsed many times. To force rereading of a changed module, do this:: import modname reload(modname) Warning: this technique is not 100% fool-proof. In particular, modules containing statements like :: from modname import some_objects will continue to work with the old version of the imported objects. If the module contains class definitions, existing class instances will *not* be updated to use the new class definition. This can result in the following paradoxical behaviour:: >>> import cls >>> c = cls.C() # Create an instance of C >>> reload(cls) >>> isinstance(c, cls.C) # isinstance is false?!? False The nature of the problem is made clear if you print out the class objects: >>> c.__class__ >>> cls.C python3-defaults-3.6.7/faq/windows.ht0000664000000000000000000006043613305601050014430 0ustar Title: Python Windows FAQ Content-type: text/x-rst ==================================== Python Windows FAQ ==================================== :Date: $Date: 2005-07-26 07:21:45 -0600 (Tue, 26 Jul 2005) $ :Version: $Revision: 8295 $ :Web site: http://www.python.org/ .. contents:: .. sectnum:: How do I run a Python program under Windows? ---------------------------------------------------- This is not necessarily a straightforward question. If you are already familiar with running programs from the Windows command line then everything will seem obvious; otherwise, you might need a little more guidance. There are also differences between Windows 95, 98, NT, ME, 2000 and XP which can add to the confusion. Unless you use some sort of integrated development environment, you will end up *typing* Windows commands into what is variously referred to as a "DOS window" or "Command prompt window". Usually you can create such a window from your Start menu; under Windows 2000 the menu selection is "Start | Programs | Accessories | Command Prompt". You should be able to recognize when you have started such a window because you will see a Windows "command prompt", which usually looks like this:: C:\> The letter may be different, and there might be other things after it, so you might just as easily see something like:: D:\Steve\Projects\Python> depending on how your computer has been set up and what else you have recently done with it. Once you have started such a window, you are well on the way to running Python programs. You need to realize that your Python scripts have to be processed by another program called the Python interpreter. The interpreter reads your script, compiles it into bytecodes, and then executes the bytecodes to run your program. So, how do you arrange for the interpreter to handle your Python? First, you need to make sure that your command window recognises the word "python" as an instruction to start the interpreter. If you have opened a command window, you should try entering the command ``python`` and hitting return. You should then see something like:: Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> You have started the interpreter in "interactive mode". That means you can enter Python statements or expressions interactively and have them executed or evaluated while you wait. This is one of Python's strongest features. Check it by entering a few expressions of your choice and seeing the results:: >>> print "Hello" Hello >>> "Hello" * 3 HelloHelloHello Many people use the interactive mode as a convenient yet highly programmable calculator. When you want to end your interactive Python session, hold the Ctrl key down while you enter a Z, then hit the "Enter" key to get back to your Windows command prompt. You may also find that you have a Start-menu entry such as "Start | Programs | Python 2.2 | Python (command line)" that results in you seeing the ``>>>`` prompt in a new window. If so, the window will disappear after you enter the Ctrl-Z character; Windows is running a single "python" command in the window, and closes it when you terminate the interpreter. If the ``python`` command, instead of displaying the interpreter prompt ``>>>``, gives you a message like:: 'python' is not recognized as an internal or external command, operable program or batch file. or:: Bad command or filename then you need to make sure that your computer knows where to find the Python interpreter. To do this you will have to modify a setting called PATH, which is a list of directories where Windows will look for programs. You should arrange for Python's installation directory to be added to the PATH of every command window as it starts. If you installed Python fairly recently then the command :: dir C:\py* will probably tell you where it is installed; the usual location is something like ``C:\Python23``. Otherwise you will be reduced to a search of your whole disk ... use "Tools | Find" or hit the "Search" button and look for "python.exe". Supposing you discover that Python is installed in the ``C:\Python23`` directory (the default at the time of writing), you should make sure that entering the command :: c:\Python23\python starts up the interpreter as above (and don't forget you'll need a "CTRL-Z" and an "Enter" to get out of it). Once you have verified the directory, you need to add it to the start-up routines your computer goes through. For older versions of Windows the easiest way to do this is to edit the ``C:\AUTOEXEC.BAT`` file. You would want to add a line like the following to ``AUTOEXEC.BAT``:: PATH C:\Python23;%PATH% For Windows NT, 2000 and (I assume) XP, you will need to add a string such as :: ;C:\Python23 to the current setting for the PATH environment variable, which you will find in the properties window of "My Computer" under the "Advanced" tab. Note that if you have sufficient privilege you might get a choice of installing the settings either for the Current User or for System. The latter is preferred if you want everybody to be able to run Python on the machine. If you aren't confident doing any of these manipulations yourself, ask for help! At this stage you may want to reboot your system to make absolutely sure the new setting has taken effect. You probably won't need to reboot for Windows NT, XP or 2000. You can also avoid it in earlier versions by editing the file ``C:\WINDOWS\COMMAND\CMDINIT.BAT`` instead of ``AUTOEXEC.BAT``. You should now be able to start a new command window, enter ``python`` at the ``C:>`` (or whatever) prompt, and see the ``>>>`` prompt that indicates the Python interpreter is reading interactive commands. Let's suppose you have a program called ``pytest.py`` in directory ``C:\Steve\Projects\Python``. A session to run that program might look like this:: C:\> cd \Steve\Projects\Python C:\Steve\Projects\Python> python pytest.py Because you added a file name to the command to start the interpreter, when it starts up it reads the Python script in the named file, compiles it, executes it, and terminates, so you see another ``C:\>`` prompt. You might also have entered :: C:\> python \Steve\Projects\Python\pytest.py if you hadn't wanted to change your current directory. Under NT, 2000 and XP you may well find that the installation process has also arranged that the command ``pytest.py`` (or, if the file isn't in the current directory, ``C:\Steve\Projects\Python\pytest.py``) will automatically recognize the ".py" extension and run the Python interpreter on the named file. Using this feature is fine, but *some* versions of Windows have bugs which mean that this form isn't exactly equivalent to using the interpreter explicitly, so be careful. The important things to remember are: 1. Start Python from the Start Menu, or make sure the PATH is set correctly so Windows can find the Python interpreter. :: python should give you a '>>>" prompt from the Python interpreter. Don't forget the CTRL-Z and ENTER to terminate the interpreter (and, if you started the window from the Start Menu, make the window disappear). 2. Once this works, you run programs with commands:: python {program-file} 3. When you know the commands to use you can build Windows shortcuts to run the Python interpreter on any of your scripts, naming particular working directories, and adding them to your menus. Take a look at :: python --help if your needs are complex. 4. Interactive mode (where you see the ``>>>`` prompt) is best used for checking that individual statements and expressions do what you think they will, and for developing code by experiment. How do I make python scripts executable? ---------------------------------------------- On Windows 2000, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (D:\\Program Files\\Python\\python.exe "%1" %*). This is enough to make scripts executable from the command prompt as 'foo.py'. If you'd rather be able to execute the script by simple typing 'foo' with no extension you need to add .py to the PATHEXT environment variable. On Windows NT, the steps taken by the installer as described above allow you to run a script with 'foo.py', but a longtime bug in the NT command processor prevents you from redirecting the input or output of any script executed in this way. This is often important. The incantation for making a Python script executable under WinNT is to give the file an extension of .cmd and add the following as the first line:: @setlocal enableextensions & python -x %~f0 %* & goto :EOF Why does Python sometimes take so long to start? ------------------------------------------------------- Usually Python starts very quickly on Windows, but occasionally there are bug reports that Python suddenly begins to take a long time to start up. This is made even more puzzling because Python will work fine on other Windows systems which appear to be configured identically. The problem may be caused by a misconfiguration of virus checking software on the problem machine. Some virus scanners have been known to introduce startup overhead of two orders of magnitude when the scanner is configured to monitor all reads from the filesystem. Try checking the configuration of virus scanning software on your systems to ensure that they are indeed configured identically. McAfee, when configured to scan all file system read activity, is a particular offender. Where is Freeze for Windows? ------------------------------------ "Freeze" is a program that allows you to ship a Python program as a single stand-alone executable file. It is *not* a compiler; your programs don't run any faster, but they are more easily distributable, at least to platforms with the same OS and CPU. Read the README file of the freeze program for more disclaimers. You can use freeze on Windows, but you must download the source tree (see http://www.python.org/download/download_source.html). The freeze program is in the ``Tools\freeze`` subdirectory of the source tree. You need the Microsoft VC++ compiler, and you probably need to build Python. The required project files are in the PCbuild directory. Is a ``*.pyd`` file the same as a DLL? ------------------------------------------ Yes, .pyd files are dll's, but there are a few differences. If you have a DLL named ``foo.pyd``, then it must have a function initfoo(). You can then write Python "import foo", and Python will search for foo.pyd (as well as foo.py, foo.pyc) and if it finds it, will attempt to call initfoo() to initialize it. You do not link your .exe with foo.lib, as that would cause Windows to require the DLL to be present. Note that the search path for foo.pyd is PYTHONPATH, not the same as the path that Windows uses to search for foo.dll. Also, foo.pyd need not be present to run your program, whereas if you linked your program with a dll, the dll is required. Of course, foo.pyd is required if you want to say "import foo". In a DLL, linkage is declared in the source code with __declspec(dllexport). In a .pyd, linkage is defined in a list of available functions. How can I embed Python into a Windows application? ---------------------------------------------------------- Embedding the Python interpreter in a Windows app can be summarized as follows: 1. Do _not_ build Python into your .exe file directly. On Windows, Python must be a DLL to handle importing modules that are themselves DLL's. (This is the first key undocumented fact.) Instead, link to pythonNN.dll; it is typically installed in ``C:\Windows\System``. NN is the Python version, a number such as "23" for Python 2.3. You can link to Python statically or dynamically. Linking statically means linking against pythonNN.lib, while dynamically linking means linking against pythonNN.dll. The drawback to dynamic linking is that your app won't run if pythonNN.dll does not exist on your system. (General note: pythonNN.lib is the so-called "import lib" corresponding to python.dll. It merely defines symbols for the linker.) Linking dynamically greatly simplifies link options; everything happens at run time. Your code must load pythonNN.dll using the Windows LoadLibraryEx() routine. The code must also use access routines and data in pythonNN.dll (that is, Python's C API's) using pointers obtained by the Windows GetProcAddress() routine. Macros can make using these pointers transparent to any C code that calls routines in Python's C API. Borland note: convert pythonNN.lib to OMF format using Coff2Omf.exe first. 2. If you use SWIG, it is easy to create a Python "extension module" that will make the app's data and methods available to Python. SWIG will handle just about all the grungy details for you. The result is C code that you link *into* your .exe file (!) You do _not_ have to create a DLL file, and this also simplifies linking. 3. SWIG will create an init function (a C function) whose name depends on the name of the extension module. For example, if the name of the module is leo, the init function will be called initleo(). If you use SWIG shadow classes, as you should, the init function will be called initleoc(). This initializes a mostly hidden helper class used by the shadow class. The reason you can link the C code in step 2 into your .exe file is that calling the initialization function is equivalent to importing the module into Python! (This is the second key undocumented fact.) 4. In short, you can use the following code to initialize the Python interpreter with your extension module. :: #include "python.h" ... Py_Initialize(); // Initialize Python. initmyAppc(); // Initialize (import) the helper class. PyRun_SimpleString("import myApp") ; // Import the shadow class. 5. There are two problems with Python's C API which will become apparent if you use a compiler other than MSVC, the compiler used to build pythonNN.dll. Problem 1: The so-called "Very High Level" functions that take FILE * arguments will not work in a multi-compiler environment because each compiler's notion of a struct FILE will be different. From an implementation standpoint these are very _low_ level functions. Problem 2: SWIG generates the following code when generating wrappers to void functions:: Py_INCREF(Py_None); _resultobj = Py_None; return _resultobj; Alas, Py_None is a macro that expands to a reference to a complex data structure called _Py_NoneStruct inside pythonNN.dll. Again, this code will fail in a mult-compiler environment. Replace such code by:: return Py_BuildValue(""); It may be possible to use SWIG's %typemap command to make the change automatically, though I have not been able to get this to work (I'm a complete SWIG newbie). 6. Using a Python shell script to put up a Python interpreter window from inside your Windows app is not a good idea; the resulting window will be independent of your app's windowing system. Rather, you (or the wxPythonWindow class) should create a "native" interpreter window. It is easy to connect that window to the Python interpreter. You can redirect Python's i/o to _any_ object that supports read and write, so all you need is a Python object (defined in your extension module) that contains read() and write() methods. How do I use Python for CGI? ------------------------------------------------------- On the Microsoft IIS server or on the Win95 MS Personal Web Server you set up Python in the same way that you would set up any other scripting engine. Run regedt32 and go to:: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters\ScriptMap and enter the following line (making any specific changes that your system may need):: .py :REG_SZ: c:\\python.exe -u %s %s This line will allow you to call your script with a simple reference like: http://yourserver/scripts/yourscript.py provided "scripts" is an "executable" directory for your server (which it usually is by default). The "-u" flag specifies unbuffered and binary mode for stdin - needed when working with binary data. In addition, it is recommended that using ".py" may not be a good idea for the file extensions when used in this context (you might want to reserve ``*.py`` for support modules and use ``*.cgi`` or ``*.cgp`` for "main program" scripts). In order to set up Internet Information Services 5 to use Python for CGI processing, please see the following links: http://www.e-coli.net/pyiis_server.html (for Win2k Server) http://www.e-coli.net/pyiis.html (for Win2k pro) Configuring Apache is much simpler. In the Apache configuration file ``httpd.conf``, add the following line at the end of the file:: ScriptInterpreterSource Registry Then, give your Python CGI-scripts the extension .py and put them in the cgi-bin directory. How do I keep editors from inserting tabs into my Python source? ------------------------------------------------------------------ The FAQ does not recommend using tabs, and `the Python style guide `_ recommends 4 spaces for distributed Python code; this is also the Emacs python-mode default. Under any editor, mixing tabs and spaces is a bad idea. MSVC is no different in this respect, and is easily configured to use spaces: Take Tools -> Options -> Tabs, and for file type "Default" set "Tab size" and "Indent size" to 4, and select the "Insert spaces" radio button. If you suspect mixed tabs and spaces are causing problems in leading whitespace, run Python with the -t switch or run ``Tools/Scripts/tabnanny.py`` to check a directory tree in batch mode. How do I check for a keypress without blocking? ---------------------------------------------------- Use the msvcrt module. This is a standard Windows-specific extension module. It defines a function kbhit() which checks whether a keyboard hit is present, and getch() which gets one character without echoing it. How do I emulate os.kill() in Windows? --------------------------------------------- Use win32api:: def kill(pid): """kill function for Win32""" import win32api handle = win32api.OpenProcess(1, 0, pid) return (0 != win32api.TerminateProcess(handle, 0)) Why does os.path.isdir() fail on NT shared directories? -------------------------------------------------------------- The solution appears to be always append the "\\" on the end of shared drives. :: >>> import os >>> os.path.isdir( '\\\\rorschach\\public') 0 >>> os.path.isdir( '\\\\rorschach\\public\\') 1 It helps to think of share points as being like drive letters. Example:: k: is not a directory k:\ is a directory k:\media is a directory k:\media\ is not a directory The same rules apply if you substitute "k:" with "\\conky\foo":: \\conky\foo is not a directory \\conky\foo\ is a directory \\conky\foo\media is a directory \\conky\foo\media\ is not a directory cgi.py (or other CGI programming) doesn't work sometimes on NT or win95! ----------------------------------------------------------------------------- Be sure you have the latest python.exe, that you are using python.exe rather than a GUI version of Python and that you have configured the server to execute :: "...\python.exe -u ..." for the CGI execution. The -u (unbuffered) option on NT and Win95 prevents the interpreter from altering newlines in the standard input and output. Without it post/multipart requests will seem to have the wrong length and binary (e.g. GIF) responses may get garbled (resulting in broken images, PDF files, and other binary downloads failing). Why doesn't os.popen() work in PythonWin on NT? ------------------------------------------------------- The reason that os.popen() doesn't work from within PythonWin is due to a bug in Microsoft's C Runtime Library (CRT). The CRT assumes you have a Win32 console attached to the process. You should use the win32pipe module's popen() instead which doesn't depend on having an attached Win32 console. Example:: import win32pipe f = win32pipe.popen('dir /c c:\\') print f.readlines() f.close() Why doesn't os.popen()/win32pipe.popen() work on Win9x? --------------------------------------------------------------- There is a bug in Win9x that prevents os.popen/win32pipe.popen* from working. The good news is there is a way to work around this problem. The Microsoft Knowledge Base article that you need to lookup is: Q150956. You will find links to the knowledge base at: http://www.microsoft.com/kb. PyRun_SimpleFile() crashes on Windows but not on Unix; why? ------------------------------------------------------------ This is very sensitive to the compiler vendor, version and (perhaps) even options. If the FILE* structure in your embedding program isn't the same as is assumed by the Python interpreter it won't work. The Python 1.5.* DLLs (``python15.dll``) are all compiled with MS VC++ 5.0 and with multithreading-DLL options (``/MD``). If you can't change compilers or flags, try using Py_RunSimpleString(). A trick to get it to run an arbitrary file is to construct a call to execfile() with the name of your file as argument. Also note that you can not mix-and-match Debug and Release versions. If you wish to use the Debug Multithreaded DLL, then your module _must_ have an "_d" appended to the base name. Importing _tkinter fails on Windows 95/98: why? ------------------------------------------------ Sometimes, the import of _tkinter fails on Windows 95 or 98, complaining with a message like the following:: ImportError: DLL load failed: One of the library files needed to run this application cannot be found. It could be that you haven't installed Tcl/Tk, but if you did install Tcl/Tk, and the Wish application works correctly, the problem may be that its installer didn't manage to edit the autoexec.bat file correctly. It tries to add a statement that changes the PATH environment variable to include the Tcl/Tk 'bin' subdirectory, but sometimes this edit doesn't quite work. Opening it with notepad usually reveals what the problem is. (One additional hint, noted by David Szafranski: you can't use long filenames here; e.g. use ``C:\PROGRA~1\Tcl\bin`` instead of ``C:\Program Files\Tcl\bin``.) How do I extract the downloaded documentation on Windows? ------------------------------------------------------------ Sometimes, when you download the documentation package to a Windows machine using a web browser, the file extension of the saved file ends up being .EXE. This is a mistake; the extension should be .TGZ. Simply rename the downloaded file to have the .TGZ extension, and WinZip will be able to handle it. (If your copy of WinZip doesn't, get a newer one from http://www.winzip.com.) Missing cw3215mt.dll (or missing cw3215.dll) ---------------------------------------------------- Sometimes, when using Tkinter on Windows, you get an error that cw3215mt.dll or cw3215.dll is missing. Cause: you have an old Tcl/Tk DLL built with cygwin in your path (probably ``C:\Windows``). You must use the Tcl/Tk DLLs from the standard Tcl/Tk installation (Python 1.5.2 comes with one). Warning about CTL3D32 version from installer ---------------------------------------------------- The Python installer issues a warning like this:: This version uses ``CTL3D32.DLL`` whitch is not the correct version. This version is used for windows NT applications only. [Tim Peters] This is a Microsoft DLL, and a notorious source of problems. The message means what it says: you have the wrong version of this DLL for your operating system. The Python installation did not cause this -- something else you installed previous to this overwrote the DLL that came with your OS (probably older shareware of some sort, but there's no way to tell now). If you search for "CTL3D32" using any search engine (AltaVista, for example), you'll find hundreds and hundreds of web pages complaining about the same problem with all sorts of installation programs. They'll point you to ways to get the correct version reinstalled on your system (since Python doesn't cause this, we can't fix it). David A Burton has written a little program to fix this. Go to http://www.burtonsys.com/download.html and click on "ctl3dfix.zip" python3-defaults-3.6.7/py3clean0000775000000000000000000001717513305601050013300 0ustar #! /usr/bin/python3 # vim: et ts=4 sw=4 # Copyright © 2010-2012 Piotr Ożarowski # # 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. import logging import optparse import sys # glob1() is not in the public documentation, UTSL. from glob import glob1 from os import environ, remove, rmdir from os.path import dirname, basename, exists, join, splitext sys.path.insert(1, '/usr/share/python3/') from debpython import files as dpf from debpython.interpreter import Interpreter from debpython.version import SUPPORTED, getver, vrepr # initialize script logging.basicConfig(format='%(levelname).1s: %(module)s:%(lineno)d: ' '%(message)s') log = logging.getLogger(__name__) """TODO: move it to manpage Examples: py3clean -p python3-mako # all .py[co] files and __pycache__ directories from the package py3clean /usr/lib/python3.1/dist-packages # python3.1 py3clean -V 3.3 /usr/lib/python3/ # python 3.3 only py3clean -V 3.3 /usr/lib/foo/bar.py # bar/__pycache__/bar.cpython-33.py[co] py3clean /usr/lib/python3/ # all Python 3.X """ def get_magic_tag_to_remove(version): """Returns magic tag or True if all of them should be removed.""" i = Interpreter('python') map_ = {} for v in SUPPORTED: try: map_[v] = i.magic_tag(v) except Exception: log.debug('magic tag for %s not recognized', vrepr(v), exc_info=True) if version not in map_: try: map_[version] = i.magic_tag(version) except Exception as e: log.error('cannot find magic tag for Python %s: %s', vrepr(version), e) exit(4) tag = map_[version] # skip shared tags for v, t in map_.items(): if v == version: continue if t == tag: log.info('magic tag(s) used by python%s. Nothing to remove.', vrepr(v)) exit(0) log.debug('magic tags to remove: %s', tag) return tag def destroyer(magic_tag=None): # ;-) """Remove every .py[co] file associated to received .py file. :param magic_tag: * If None, removes all associated .py[co] files from __pycache__ directory. If the resulting directory is empty, and is not a system site package, then the directory is also removed. * If False, removes python3.1's .pyc files only * Otherwise removes given magic tag from __pycache__ directory. If the resulting directory is empty, and is not a system site package, then the directory is also removed. :type magic_tag: None or False or str """ if magic_tag is None: # remove compiled files in __pycache__ directory def find_files_to_remove(pyfile): directory = join(dirname(pyfile), '__pycache__') fname = splitext(basename(pyfile))[0] for fn in glob1(directory, "%s.*" % fname): yield join(directory, fn) # remove "classic" .pyc files as well for filename in ("%sc" % pyfile, "%so" % pyfile): if exists(filename): yield filename # workaround for http://bugs.python.org/issue22966 if '.' in fname: sane_fname = join(dirname(pyfile), fname.split('.', 1)[0]) for fn in find_files_to_remove(sane_fname): yield join(directory, fn) elif magic_tag is False: # remove 3.1's .pyc files only def find_files_to_remove(pyfile): # NOQA for filename in ("%sc" % pyfile, "%so" % pyfile): if exists(filename): yield filename else: # remove .pyc files for no longer needed magic tags def find_files_to_remove(pyfile): # NOQA directory = join(dirname(pyfile), '__pycache__') fname = splitext(basename(pyfile))[0] for fn in glob1(directory, "%s.%s.py[co]" % (fname, magic_tag)): yield join(directory, fn) # workaround for http://bugs.python.org/issue22966 if '.' in fname: sane_fname = join(dirname(pyfile), fname.split('.', 1)[0]) for fn in find_files_to_remove(sane_fname): yield join(directory, fn) def myremove(fname): remove(fname) directory = dirname(fname) # remove __pycache__ directory if it's empty if directory.endswith('__pycache__'): try: rmdir(directory) except Exception: pass counter = 0 try: while True: pyfile = (yield) for filename in find_files_to_remove(pyfile): try: myremove(filename) counter += 1 except (IOError, OSError) as e: log.error('cannot remove %s', filename) log.debug(e) except GeneratorExit: log.info("removed files: %s", counter) def main(): usage = '%prog [-V VERSION] [-p PACKAGE] [DIR_OR_FILE]' parser = optparse.OptionParser(usage, version='%prog DEVELV') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='turn verbose mode on') parser.add_option('-q', '--quiet', action='store_false', dest='verbose', default=False, help='be quiet') parser.add_option('-p', '--package', help='specify Debian package name to clean') parser.add_option('-V', dest='version', help='specify Python version to clean') (options, args) = parser.parse_args() if options.verbose or environ.get('PYCLEAN_DEBUG') == '1': log.setLevel(logging.DEBUG) log.debug('argv: %s', sys.argv) log.debug('options: %s', options) log.debug('args: %s', args) else: log.setLevel(logging.WARNING) if options.version: if options.version.endswith('3.1'): # 3.1, -3.1 magic_tag = False else: magic_tag = get_magic_tag_to_remove(getver(options.version)) d = destroyer(magic_tag) else: d = destroyer() # remove everything next(d) # initialize coroutine if not options.package and not args: parser.print_usage() exit(1) if options.package: log.info('cleaning package %s', options.package) pfiles = set(dpf.from_package(options.package)) if args: log.info('cleaning directories: %s', args) files = set(dpf.from_directory(args)) if options.package: files = files & pfiles else: files = pfiles for filename in files: d.send(filename) if __name__ == '__main__': main() python3-defaults-3.6.7/py3clean.rst0000664000000000000000000000101713305601050014070 0ustar ========== py3clean ========== --------------------------- removes .pyc and .pyo files --------------------------- :Manual section: 1 :Author: Piotr Ożarowski, 2012-2013 SYNOPSIS ======== py3clean [-V VERSION] [-p PACKAGE] [DIR_OR_FILE] OPTIONS ======= --version show program's version number and exit -h, --help show this help message and exit -v, --verbose turn verbose more one -q, --quiet be quiet -p PACKAGE, --package=PACKAGE specify Debian package name to clean -V VERSION specify Python 3 version to clean python3-defaults-3.6.7/py3compile0000775000000000000000000002752013305601050013641 0ustar #! /usr/bin/python3 # vim: et ts=4 sw=4 # Copyright © 2010-2012 Piotr Ożarowski # Copyright © 2010 Canonical Ltd # # 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. import logging import optparse import os import struct import sys from os import environ, listdir, mkdir from os.path import dirname, exists, isdir, join from subprocess import PIPE, Popen sys.path.insert(1, '/usr/share/python3/') from debpython.version import SUPPORTED, debsorted, vrepr, \ get_requested_versions, parse_vrange, getver from debpython import files as dpf, PUBLIC_DIR_RE, memoize from debpython.interpreter import Interpreter from debpython.option import Option, compile_regexpr # initialize script logging.basicConfig(format='%(levelname).1s: %(module)s:%(lineno)d: ' '%(message)s') log = logging.getLogger(__name__) STDINS = {} WORKERS = {} """TODO: move it to manpage Examples: pycompile -p python3-mako # package's public files pycompile -p python3-foo /usr/share/foo # package's private files pycompile -V 3.1 /usr/lib/python3.1/ # python3.1 only pycompile -V 3.1 /usr/lib/foo/bar.py # python3.1 only pycompile -V 3.2- /usr/lib/python3/ """ ### EXCLUDES ################################################### @memoize def get_exclude_patterns_from_dir(name='/usr/share/python3/bcep/'): """Return patterns for files that shouldn't be bytecompiled.""" if not isdir(name): return [] result = [] for fn in listdir(name): with open(join(name, fn), 'r', encoding='utf-8') as lines: for line in lines: type_, vrange, dname, pattern = line.split('|', 3) vrange = parse_vrange(vrange) versions = get_requested_versions(vrange, available=True) if not versions: # pattern doesn't match installed Python versions continue pattern = pattern.rstrip('\n') if type_ == 're': pattern = compile_regexpr(None, None, pattern) result.append((type_, versions, dname, pattern)) return result def get_exclude_patterns(directory='/', patterns=None, versions=None): """Return patterns for files that shouldn't be compiled in given dir.""" if versions is not None: # make sure it's a set (debsorted returns a list) versions = set(versions) if patterns: if versions is None: versions = set(SUPPORTED) patterns = [('re', versions, directory, i) for i in patterns] else: patterns = [] for type_, vers, dname, pattern in get_exclude_patterns_from_dir(): # skip patterns that do not match requested directory if not dname.startswith(directory[:len(dname)]): continue # skip patterns that do not match requested versions if versions and not versions & vers: continue patterns.append((type_, vers, dname, pattern)) return patterns def filter_files(files, e_patterns, compile_versions): """Generate (file, versions_to_compile) pairs.""" for fn in files: valid_versions = set(compile_versions) # all by default for type_, vers, dname, pattern in e_patterns: if type_ == 'dir' and fn.startswith(dname): valid_versions = valid_versions - vers elif type_ == 're' and pattern.match(fn): valid_versions = valid_versions - vers # move to the next file if all versions were removed if not valid_versions: break if valid_versions: public_dir = PUBLIC_DIR_RE.match(fn) if public_dir and len(public_dir.group(1)) != 1: yield fn, set([getver(public_dir.group(1))]) else: yield fn, valid_versions ### COMPILE #################################################### def py_compile(version, optimize, workers): if not isinstance(version, str): version = vrepr(version) cmd = "/usr/bin/python%s%s -m py_compile -" \ % (version, ' -O' if optimize else '') process = Popen(cmd, bufsize=1, shell=True, stdin=PIPE, close_fds=True) workers[version] = process # keep the reference for .communicate() stdin = process.stdin while True: filename = (yield) stdin.write(filename.encode('utf-8') + b'\n') def compile(files, versions, force, optimize, e_patterns=None): global STDINS, WORKERS # start Python interpreters that will handle byte compilation for version in versions: if version not in STDINS: coroutine = py_compile(version, optimize, WORKERS) next(coroutine) STDINS[version] = coroutine interpreter = Interpreter('python' if not optimize else 'python -O') # byte compile files skip_dirs = set() for fn, versions_to_compile in filter_files(files, e_patterns, versions): for version in versions_to_compile: cfn = interpreter.cache_file(fn, version) if version == (3, 1): if exists(cfn) and not force: ftime = os.stat(fn).st_mtime try: ctime = os.stat(cfn).st_mtime except os.error: ctime = 0 if ctime > ftime: continue else: pycache_dir = dirname(cfn) if not force: try: mtime = int(os.stat(fn).st_mtime) expect = struct.pack('<4sl', interpreter.magic_number(version), mtime) with open(cfn, 'rb') as chandle: actual = chandle.read(8) if expect == actual: continue except (IOError, OSError): pass if pycache_dir not in skip_dirs and not exists(pycache_dir): try: mkdir(pycache_dir) except Exception as e: log.error("cannot create directory %s: %r", pycache_dir, e) skip_dirs.add(pycache_dir) continue pipe = STDINS[version] pipe.send(fn) ################################################################ def main(): usage = '%prog [-V [X.Y][-][A.B]] DIR_OR_FILE [-X REGEXPR]\n' +\ ' %prog -p PACKAGE' parser = optparse.OptionParser(usage, version='%prog DEVELV', option_class=Option) parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='turn verbose mode on') parser.add_option('-q', '--quiet', action='store_false', dest='verbose', default=False, help='be quiet') parser.add_option('-f', '--force', action='store_true', dest='force', default=False, help='force rebuild even if timestamps are up-to-date') parser.add_option('-O', action='store_true', dest='optimize', default=False, help="byte-compile to .pyo files") parser.add_option('-p', '--package', help='specify Debian package name whose files should be bytecompiled') parser.add_option('-V', type='version_range', dest='vrange', help="""force private modules to be bytecompiled with Python version from given range, regardless of the default Python version in the system. If there are no other options, bytecompile all public modules for installed Python versions that match given range. VERSION_RANGE examples: '3.1' (version 3.1 only), '3.1-' (version 3.1 or newer), '3.1-3.3' (version 3.1 or 3.2), '-4.0' (all supported 3.X versions)""") parser.add_option('-X', '--exclude', action='append', dest='regexpr', type='regexpr', help='exclude items that match given REGEXPR. \ You may use this option multiple times to build up a list of things to exclude.') (options, args) = parser.parse_args() if options.verbose or environ.get('PYCOMPILE_DEBUG') == '1': log.setLevel(logging.DEBUG) log.debug('argv: %s', sys.argv) log.debug('options: %s', options) log.debug('args: %s', args) else: log.setLevel(logging.WARN) if options.regexpr and not args: parser.error('--exclude option works with private directories ' 'only, please use /usr/share/python3/bcep to specify ' 'public modules to skip') if options.vrange and options.vrange[0] == options.vrange[1] and\ options.vrange != (None, None) and\ exists("/usr/bin/python%d.%d" % options.vrange[0]): # specific version requested, use it even if it's not in SUPPORTED versions = {options.vrange[0]} else: versions = get_requested_versions(options.vrange, available=True) if not versions: log.error('Requested versions are not installed') exit(3) if options.package and args: # package's private directories # get requested Python version compile_versions = debsorted(versions)[:1] log.debug('compile versions: %s', versions) pkg_files = tuple(dpf.from_package(options.package)) for item in args: e_patterns = get_exclude_patterns(item, options.regexpr, compile_versions) if not exists(item): log.warn('No such file or directory: %s', item) else: log.debug('byte compiling %s using Python %s', item, compile_versions) files = dpf.filter_directory(pkg_files, item) compile(files, compile_versions, options.force, options.optimize, e_patterns) elif options.package: # package's public modules # no need to limit versions here, it's either pyr mode or version is # hardcoded in path / via -V option e_patterns = get_exclude_patterns() files = dpf.from_package(options.package) files = dpf.filter_public(files, versions) compile(files, versions, options.force, options.optimize, e_patterns) elif args: # other directories/files for item in args: e_patterns = get_exclude_patterns(item, options.regexpr, versions) files = dpf.from_directory(item) compile(files, versions, options.force, options.optimize, e_patterns) else: parser.print_usage() exit(1) # wait for all processes to finish rv = 0 for process in WORKERS.values(): process.communicate() if process.returncode not in (None, 0): rv = process.returncode exit(rv) if __name__ == '__main__': main() python3-defaults-3.6.7/py3compile.rst0000664000000000000000000000255713305601050014450 0ustar ============ py3compile ============ ---------------------------------- byte compile Python 3 source files ---------------------------------- :Manual section: 1 :Author: Piotr Ożarowski, 2012-2013 SYNOPSIS ======== py3compile [-V [X.Y][-][A.B]] DIR_OR_FILE [-X REGEXPR] pycompile -p PACKAGE DESCRIPTION =========== Wrapper around Python standard library's py_compile module to byte-compile Python 3 files. OPTIONS ======= --version show program's version number and exit -h, --help show this help message and exit -f, --force force rebuild of byte-code files even if timestamps are up-to-date -O byte-compile to .pyo files -q, --quiet be quiet -v, --verbose turn verbose mode on -p PACKAGE, --package=PACKAGE specify Debian package name whose files should be bytecompiled -V VRANGE force private modules to be bytecompiled with Python 3 version from given range, regardless of the default Python 3 version in the system. If there are no other options, bytecompile all public modules for installed Python 3 versions that match given range. VERSION_RANGE examples: * ``3.1`` version 3.1 only, * ``3.1-`` version 3.1 or newer, * ``3.1-3.3`` version 3.1 or 3.2, * ``-4.0`` all supported 3.X versions -X REGEXPR, --exclude=REGEXPR exclude items that match given REGEXPR. You may use this option multiple times to build up a list of things to exclude python3-defaults-3.6.7/runtime.d/0000775000000000000000000000000013305601050013526 5ustar python3-defaults-3.6.7/runtime.d/public_modules.rtinstall0000775000000000000000000000033213305601050020473 0ustar #! /bin/sh set -e VERSION=${2#python} if which py3compile >/dev/null 2>&1; then py3compile -V $VERSION /usr/lib/python3/dist-packages else echo >&2 "py3compile not found in $(basename $0) hook." exit 1 fi python3-defaults-3.6.7/runtime.d/public_modules.rtremove0000775000000000000000000000121313305601050020321 0ustar #! /bin/sh set -e VERSION=${2#python} if which py3clean >/dev/null 2>&1; then if [ "$VERSION" = 3.1 ]; then find /usr/lib/python3.1/dist-packages -name '*.py[co]' -delete find /usr/lib/python3/dist-packages -name '*.py[co]' -delete else py3clean -V $VERSION /usr/lib/python3/dist-packages fi else if [ "$VERSION" = 3.1 ]; then find /usr/lib/python3.1/dist-packages -name '*.py[co]' -delete else TAG=`python$VERSION -c "import imp; print(imp.magic_tags[imp.get_magic()])"` \ find /usr/lib/python3/dist-packages -name "*.$TAG.py[co]" -delete find /usr/lib/python3/dist-packages -depth -empty -name '__pycache__' -delete fi fi