pax_global_header00006660000000000000000000000064132363270310014512gustar00rootroot0000000000000052 comment=4a1ded353923b143a2d4373b11c9592ea27fd5d6 py3c-1.0/000077500000000000000000000000001323632703100122305ustar00rootroot00000000000000py3c-1.0/.gitignore000066400000000000000000000001041323632703100142130ustar00rootroot00000000000000/doc/build/ /test/build/ __pycache__/ /py3c.pc .eggs dist *.egg-infopy3c-1.0/.travis.yml000066400000000000000000000005011323632703100143350ustar00rootroot00000000000000language: python python: - "2.6" - "2.7" - "3.3" - "3.4" - "3.5" - "3.5" - "3.6" - "nightly" env: - TEST_USE_CPP=no CFLAGS="-Werror -Wall -std=c90 -Wno-error=strict-aliasing" - TEST_USE_CPP=yes CFLAGS="-Werror -Wall -Wno-error=strict-aliasing" script: make test-python sudo: false py3c-1.0/CHANGELOG.rst000077700000000000000000000000001323632703100207722doc/source/changelog.rstustar00rootroot00000000000000py3c-1.0/CONTRIBUTING000077700000000000000000000000001323632703100213632doc/source/contributing.rstustar00rootroot00000000000000py3c-1.0/LICENSE.MIT000066400000000000000000000020751323632703100136710ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2015, py3c contributors 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. py3c-1.0/Makefile000066400000000000000000000023141323632703100136700ustar00rootroot00000000000000all: echo "Available targets:" echo " make test" echo " make test-" echo " make doc" echo " make install" echo " make clean" prefix ?= /usr/local includedir ?= $(prefix)/include datarootdir ?= $(prefix)/share datadir ?= $(datarootdir) pkgconfigdir ?= ${datadir}/pkgconfig doc: cd doc && $(MAKE) html test: $(MAKE) test-python2 $(MAKE) test-python3 $(MAKE) test-python2-cpp $(MAKE) test-python3-cpp # TODO: A better way to build & use one-off extensions? build-%: cd test; rm -rvf build ; $* setup.py build build-%-cpp: cd test; rm -rvf build ; TEST_USE_CPP=yes $* setup.py build test-%: build-% PYTHONPATH=$(wildcard test/build/lib*) $* test -v test-%-cpp: build-%-cpp TEST_USE_CPP=yes PYTHONPATH=$(wildcard test/build/lib*) $* test -v $(includedir): mkdir -p $(includedir) py3c.pc: py3c.pc.in $(includedir) sed -e's:@includedir@:$(realpath $(includedir)):' $< > $@ install: py3c.pc mkdir -p -m 0755 $(includedir)/py3c install -m 0644 include/py3c.h $(includedir)/py3c.h install -m 0644 $(wildcard include/py3c/*.h) $(includedir)/py3c/ mkdir -p -m 0755 $(pkgconfigdir) install -m 0644 py3c.pc $(pkgconfigdir)/ clean: rm py3c.pc ||: .PHONY: test doc clean install py3c-1.0/README.rst000066400000000000000000000027571323632703100137320ustar00rootroot00000000000000py3c ==== py3c helps you port C extensions to Python 3. It provides a detailed guide, and a set of macros to make porting easy and reduce boilerplate. Design principles ----------------- * Reduce chances of accidental subtle errors * Minimize boilerplate * Prefer the Python 3 way of doing things * Minimize semantic changes under Python 2 Versions -------- Projects using py3c will be compatible with CPython 2.6, 2.7, and 3.3+. Guides ------ A detailed `porting guide`_ is provided. A `cheatsheet`_ is available for those that already know the Python C API, and want to know what the py3c macros do. .. _porting guide: http://py3c.readthedocs.org/en/latest/guide.html .. _cheatsheet: http://py3c.readthedocs.org/en/latest/cheatsheet.html Installation ------------ If your build system supports pkg-config, you can set it up to look for a system-wide installation of py3c. Alternately, py3c can be used as a header-only library: copy the headers to your project and use them. If you wish to install py3c system-wide (e.g. if you are a distro packager), see the Contributing_ chapter in the documentation. .. _Contributing: http://py3c.readthedocs.org/en/latest/contributing.html Contribute ---------- - Issue Tracker: http://github.com/encukou/py3c/issues - Source Code: http://github.com/encukou/py3c License ------- The code is licensed under the MIT license. May it serve you well. The documentation is licensed under CC-BY-SA 3.0. See the files LICENSE.MIT and doc/LICENSE.CC-BY-SA-3.0. py3c-1.0/doc/000077500000000000000000000000001323632703100127755ustar00rootroot00000000000000py3c-1.0/doc/LICENSE.CC-BY-SA-3.0000066400000000000000000000513541323632703100154050ustar00rootroot00000000000000Attribution-ShareAlike 3.0 Unported CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM ITS USE. License THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. 1. Definitions 1. "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License. 2. "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined below) for the purposes of this License. 3. "Creative Commons Compatible License" means a license that is listed at http://creativecommons.org/compatiblelicenses that has been approved by Creative Commons as being essentially equivalent to this License, including, at a minimum, because that license: (i) contains terms that have the same purpose, meaning and effect as the License Elements of this License; and, (ii) explicitly permits the relicensing of adaptations of works made available under that license under this License or a Creative Commons jurisdiction license with the same License Elements as this License. 4. "Distribute" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership. 5. "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike. 6. "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License. 7. "Original Author" means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast. 8. "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work. 9. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. 10. "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images. 11. "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium. 2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws. 3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: 1. to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections; 2. to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified."; 3. to Distribute and Publicly Perform the Work including as incorporated in Collections; and, 4. to Distribute and Publicly Perform Adaptations. 5. For the avoidance of doubt: 1. Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; 2. Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and, 3. Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License. The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved. 4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: 1. You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(c), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(c), as requested. 2. You may Distribute or Publicly Perform an Adaptation only under the terms of: (i) this License; (ii) a later version of this License with the same License Elements as this License; (iii) a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible License. If you license the Adaptation under one of the licenses mentioned in (iv), you must comply with the terms of that license. If you license the Adaptation under the terms of any of the licenses mentioned in (i), (ii) or (iii) (the "Applicable License"), you must comply with the terms of the Applicable License generally and the following provisions: (I) You must include a copy of, or the URI for, the Applicable License with every copy of each Adaptation You Distribute or Publicly Perform; (II) You may not offer or impose any terms on the Adaptation that restrict the terms of the Applicable License or the ability of the recipient of the Adaptation to exercise the rights granted to that recipient under the terms of the Applicable License; (III) You must keep intact all notices that refer to the Applicable License and to the disclaimer of warranties with every copy of the Work as included in the Adaptation You Distribute or Publicly Perform; (IV) when You Distribute or Publicly Perform the Adaptation, You may not impose any effective technological measures on the Adaptation that restrict the ability of a recipient of the Adaptation from You to exercise the rights granted to that recipient under the terms of the Applicable License. This Section 4(b) applies to the Adaptation as incorporated in a Collection, but this does not require the Collection apart from the Adaptation itself to be made subject to the terms of the Applicable License. 3. If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Ssection 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties. 4. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise. 5. Representations, Warranties and Disclaimer UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. 6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. Termination 1. This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. 2. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. 8. Miscellaneous 1. Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. 2. Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. 3. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. 4. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. 5. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. 6. The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law. Creative Commons Notice Creative Commons is not a party to this License, and makes no warranty whatsoever in connection with the Work. Creative Commons will not be liable to You or any party on any legal theory for any damages whatsoever, including without limitation any general, special, incidental or consequential damages arising in connection to this license. Notwithstanding the foregoing two (2) sentences, if Creative Commons has expressly identified itself as the Licensor hereunder, it shall have all rights and obligations of Licensor. Except for the limited purpose of indicating to the public that the Work is licensed under the CCPL, Creative Commons does not authorize the use by either party of the trademark "Creative Commons" or any related trademark or logo of Creative Commons without the prior written consent of Creative Commons. Any permitted use will be in compliance with Creative Commons' then-current trademark usage guidelines, as may be published on its website or otherwise made available upon request from time to time. For the avoidance of doubt, this trademark restriction does not form part of the License. Creative Commons may be contacted at http://creativecommons.org/. py3c-1.0/doc/Makefile000066400000000000000000000151531323632703100144420ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/py3c.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/py3c.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/py3c" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/py3c" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." py3c-1.0/doc/source/000077500000000000000000000000001323632703100142755ustar00rootroot00000000000000py3c-1.0/doc/source/capsulethunk.rst000066400000000000000000000070031323632703100175350ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Copyright (c) 2001-2015 Python Software Foundation; All Rights Reserved Licensed under CC-BY-SA-3.0; see the license file .. highlight:: c PyCapsule API for Python 2.6 ============================ The ``capsulethunk.h`` header implements the PyCapsule API (with some limitations) in terms of PYCObject. It is only necessary for compatibility with Python 2.6 (or 3.0). .. note:: The ``capsulethunk.h`` header and this documentation was written by Larry Hastings for the Python documentation. [#issue13053]_ It is now maintained as part of the py3c project. [#issue24937]_ .. index:: single: capsulethunk CObject replaced with Capsule ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The :c:type:`Capsule ` object was introduced in Python 3.1 and 2.7 to replace :c:type:`CObject `. CObjects were useful, but the :c:type:`CObject ` API was problematic: it didn't permit distinguishing between valid CObjects, which allowed mismatched CObjects to crash the interpreter, and some of its APIs relied on undefined behavior in C. (For further reading on the rationale behind Capsules, please see `CPython issue 5630 `_.) If you're currently using CObjects, and you want to migrate to Python 3, you'll need to switch to Capsules. See the :ref:`PyCObject section ` in the porting guide for instructions. :c:type:`CObject ` was deprecated in 3.1 and 2.7 and completely removed in Python 3.2. So, if you need to support versions of Python earlier than 2.7, or Python 3.0, you'll have to support both CObjects and Capsules. The following example header file :file:`capsulethunk.h` may solve the problem for you. Simply write your code against the :c:type:`Capsule ` API and include this header file after :file:`Python.h`. Your code will automatically use Capsules in versions of Python with Capsules, and switch to CObjects when Capsules are unavailable. If you're using py3c, you will need to explicitly ``#include ``. The file is not included from ``py3c.h``. Since :c:type:`CObject ` provides no place to store the capsule's "name", the simulated :c:type:`Capsule ` objects created by :file:`capsulethunk.h` behave slightly differently from real Capsules. Specifically: * The name parameter passed in to :c:func:`PyCapsule_New` is ignored. * The name parameter passed in to :c:func:`PyCapsule_IsValid` and :c:func:`PyCapsule_GetPointer` is ignored, and no error checking of the name is performed. * :c:func:`PyCapsule_GetName` always returns NULL. * :c:func:`PyCapsule_SetName` always raises an exception and returns failure. (Since there's no way to store a name in a CObject, noisy failure of :c:func:`PyCapsule_SetName` was deemed preferable to silent failure here.) If this is inconvenient, feel free to modify your local copy as you see fit. You can find :file:`capsulethunk.h` at `include/py3c/capsulethunk.h `_. We also include it here for your convenience: .. literalinclude:: ../../include/py3c/capsulethunk.h --------- .. rubric:: Footnotes .. [#issue13053] `CPython issue 13053 `_: Add Capsule migration documentation to "cporting" .. [#issue24937] `CPython issue 24937 `_: Multiple problems in getters & setters in capsulethunk.h py3c-1.0/doc/source/changelog.rst000066400000000000000000000042211323632703100167550ustar00rootroot00000000000000 ============ py3c Changes ============ Version History =============== v1.0 (2018-02-06) ----------------- Additions: * Add Py_UNREACHABLE from Python 3.7 * Add Py_RETURN_RICHCOMPARE from Python 3.7 * Add Py_UNUSED from Python 3.4 Deprecations: * The macro PY3C_RICHCMP is deprecated in favor of Py_RETURN_RICHCOMPARE. There are no plans to remove the old macro from py3c. Fixes: * The PyStr_Concat function no longer causes GCC warnings about being unused. Tests: * The test suite now fails on unexpected compiler warnings. Packaging: * py3c is now on PyPI, thanks to @xoviat v0.9 (2017-11-08) ----------------- Tests: * Adapt tests to Python 3.7 regarding const correctness (thanks to Marcel Plch) Build: * Fix includedir substitution on OS X (thanks to Branko Čibej) (This might cause make to fail if includedir, by default /usr/local/include, is not present; in that case it needs to be created.) v0.8 (2017-02-01) ----------------- Additions: * Add backports for PyMem_Raw* Compatibility: * Restore compatibility with old Visual Studio versions * Enable tests on Python 3.6 v0.7 (2016-07-05) ----------------- Packaging: * Fix file shim tests on big endian architectures (bug in testsuite only) v0.6 (2016-05-19) ----------------- Packaging: * Fix file permissions when doing ``make instal`` v0.5 (2016-05-13) ----------------- Packaging: * Fix the pkgconfig file v0.4 (2016-05-13) ----------------- Fixes: * Fix unterminated #if in tpflags.h (thanks to MURAOKA Yusuke) Additions: * Support for C++ (with initial help from MURAOKA Yusuke) * Support PyFloat_FromString (thanks to Christoph Zwerschke) * Test suite is much more comprehensive v0.3 (2015-09-09) ----------------- Breaking changes: * Type flags moved to "tpflags.h", which is not included by default. See the warning in the file, or in documentation. Other changes: * Integrated capsulethunk.h * Added PyFile_AsFile shim * Discuss porting type definitions in the guide v0.2 (2015-08-25) ----------------- * First tagged public release More Details ============ For all changes, see the `commit history on Github `_. py3c-1.0/doc/source/cheatsheet.rst000066400000000000000000000041211323632703100171420ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Licensed under CC-BY-SA-3.0; see the license file ~~~~~~~~~~~~~~~~~~~ The py3c Cheatsheet ~~~~~~~~~~~~~~~~~~~ Strings ~~~~~~~ * PyStr_* – for human-readable strings * PyBytes_* – for binary data * PyUnicode_* – when you used ``unicode`` in Python 2 * PyString_* – when you don't care about Python 3 yet Use PyStr_AsUTF8AndSize to get a char* and its length. Ints ~~~~ Use whatever you used in Python 2. For py3-only code, use ``PyLong``. Floats ~~~~~~ Don't pass the useless second argument to :c:func:`PyFloat_FromString` as you needed to do in Python 2. Comparisons ~~~~~~~~~~~ Use `rich comparisons `_:: static PyObject* mytype_richcmp(PyObject *obj1, PyObject *obj2, int op) { if (mytype_Check(obj2)) { PY_RETURN_RICHCOMPARE(get_data(obj1), get_data(obj2), op); } Py_RETURN_NOTIMPLEMENTED; } :: .tp_richcompare = mytype_richcmp Objects & Types ~~~~~~~~~~~~~~~ ============================== ================================ Instead of use ============================== ================================ obj->ob_type Py_TYPE(obj) obj->ob_refcnt Py_REFCNT(obj) obj->ob_size Py_SIZE(obj) PyVarObject_HEAD_INIT(NULL, 0) PyObject_HEAD_INIT(NULL), 0 ============================== ================================ Module initialization ~~~~~~~~~~~~~~~~~~~~~ :: static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, .m_name = "spam", .m_doc = PyDoc_STR("Python wrapper for the spam submodule."), .m_size = -1, .m_methods = spam_methods, }; MODULE_INIT_FUNC(name) { ... m = PyModule_Create(&moduledef); ... if (error) { return NULL; } ... return m; } CObject ~~~~~~~ Use the `PyCapsule `_ API. If you need to support 2.6, see the chapter :doc:`capsulethunk`. py3c-1.0/doc/source/conf.py000066400000000000000000000207521323632703100156020ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # py3c documentation build configuration file, created by # sphinx-quickstart on Thu Mar 19 17:38:06 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.intersphinx', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'py3c' copyright = u'2015, Red Hat, Inc. and/or its affiliates' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.0' # The full version, including alpha/beta/rc tags. release = '1.0a1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # only import and set the theme if we're building docs locally if not os.environ.get('READTHEDOCS', None): try: import sphinx_rtd_theme except ():#ImportError: pass 1/0 else: html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'py3cdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'py3c.tex', u'py3c Documentation', u'Petr Viktorin', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'py3c', u'py3c Documentation', [u'Petr Viktorin'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'py3c', u'py3c Documentation', u'Petr Viktorin', 'py3c', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'py3': ('https://docs.python.org/3', None), 'py2': ('https://docs.python.org/2', None), } py3c-1.0/doc/source/contributing.rst000066400000000000000000000031561323632703100175430ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Licensed under CC-BY-SA-3.0; see the license file ==================== Contributing to py3c ==================== .. highlight:: c If you would like to contribute to py3c, be it code, documentation, suggestions, or anything else, please file an issue or send a pull request at the project's `Github page `_. If you are not familiar with Github, or prefer not to use it, you can e-mail contributions to ``encukou`` at ``gmail`` dot ``com``. Testing ======= Automatic testing is set up at Travis CI: .. image:: https://travis-ci.org/encukou/py3c.svg?branch=master :alt: Build status :target: https://travis-ci.org/encukou/py3c To test the code locally, you can run (using GNU make):: $ make test This will test py3c against ``python2`` and ``python3``. To test under a different interpreter, run for example:: $ make test-python35 Packaging ========= To install system-wide (for example, if you are a distro packager), use ``make install``. There are no configure/compile steps for this header-only library. The install target honors GNU standard `environment variables`__ to specify installation directories. __ https://www.gnu.org/prep/standards/html_node/Directory-Variables.html Building the Docs ================= To build the docs, you need `Sphinx `_. If it's not in your system's package manager, it can be installed with:: $ pip install --user sphinx To build the HTML documentation, do:: $ make doc For more docs options, run `make` in the `doc` directory. py3c-1.0/doc/source/defs.rst000066400000000000000000000066061323632703100157600ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Licensed under CC-BY-SA-3.0; see the license file =================== Definitions in py3c =================== This table summarizes the various macros py3c defines, or mentions in the Porting Guide. ============================ ============= ============== Macro py2 py3 ============================ ============= ============== IS_PY3 → 0 → 1 PyStr_* → PyString_* → PyUnicode_* PyBytes_* → PyString_* ✔ PyUnicode_* ✔ ✔ PyString_* ✔ *error* PyStr_AsUTF8AndSize see below ✔ PyInt_* ✔ → PyLong_* PyLong_* ✔ ✔ PyFloat_FromString see below ✔ PyModuleDef see below ✔ PyModuleDef_HEAD_INIT → 0 ✔ PyModule_Create see below ✔ MODULE_INIT_FUNC see below see below Rich comparisons ✔ ✔ Py_RETURN_RICHCOMPARE = = Py_RETURN_NOTIMPLEMENTED = = Py_UNREACHABLE = = PY3C_RICHCMP see below see below Py_TYPE ✔ ✔ Py_REFCNT ✔ ✔ Py_SIZE ✔ ✔ PyVarObject_HEAD_INIT ✔ ✔ PyCapsule_* see below ✔ Py_TPFLAGS_* ✔ see below PyMem_Raw* = = Py_UNUSED = = ============================ ============= ============== Legend: | ✔ – provided by Python | → – defined in py3c as a simple alias for | = – provided by at least Python 3.7; py3c backports it to Python versions that don't define it The following non-trivial macros are defined: :c:func:`PyStr_AsUTF8AndSize` Python 2: defined in terms of PyString_Size and PyString_AsString. Differences from Python 3: * no encoding (string is assumed to be UTF-8-encoded) * size pointer must not be NULL * size may be stored even if an error occurs :c:func:`PyFloat_FromSting` | Python 2: Only takes one argument, as in Python 3. :c:type:`PyModuleDef` | Python 2: contains ``m_name``, ``m_doc``, ``m_size``, ``m_methods`` fields from Python 3, and ``m_base`` to accomodate PyModuleDef_HEAD_INIT. :c:func:`PyModule_Create` | Python 2: calls Py_InitModule3; semantics same as in Python 3 :c:func:`MODULE_INIT_FUNC `\ () | Python 3: declares PyInit_ and provides function header for it | Python 2: declares & defines init; declares a static PyInit_ and provides function header for it :c:func:`PY3C_RICHCMP` | Convenience macro for comparisons, same in both versions. | Deprecated; use :c:macro:`Py_RETURN_RICHCOMPARE` instead. :ref:`PyCapsule_* ` | Capsules are included in Python 2.7 and 3.1+. | For 2.6, see the chapter :doc:`capsulethunk`. :ref:`Py_TPFLAGS_* ` Type flags that were removed in Python 3 are defined to ``0`` in ````. Read the documentation before including the file. py3c-1.0/doc/source/ext-types.rst000066400000000000000000000114511323632703100167730ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Licensed under CC-BY-SA-3.0; see the license file .. highlight:: c .. index:: double: Porting; PyTypeObject ======================= Porting extension types ======================= The extension type structure, PyTypeObject, has seen some changes in Python 3. You might wish to refresh your memory with the Python documentation on this (:ref:`Python 2 `, :ref:`Python 3 `); here we concentrate only on the differences. .. _tpflags: Type Flags ========== The most common incompatibility in type definition involves feature flags like :data:`Py_TPFLAGS_HAVE_WEAKREFS` and :data:`Py_TPFLAGS_HAVE_ITER` (see :ref:`Type flags reference ` for a full list). These flags indicate capabilities that are always present in Python 3, so the macros are only available in Python 2. Most projects can simply define these to 0 in Python 3. However, another use of the macros is feature checking, as in :c:func:`PyType_HasFeature(cls, Py_TPFLAGS_HAVE_ITER) `. Defining the flags to ``0`` would cause that test to fail under Python 3, where it should instead always succeed! So, in these cases, the check should be done as ``(IS_PY3 || PyType_HasFeature(cls, Py_TPFLAGS_HAVE_ITER))``. If your project does not use ``PyType_HasFeature``, or bypasses the check under Python 3 as above, you can include ```` to define missing type flags as 0. PyTypeObject ============ The differences in PyTypeObject itself are fairly minor. The ``tp_compare`` field became ``void *tp_reserved``, and is ignored. If you use ``tp_richcompare``, this field is ignored in Python 2. It is best set to NULL. The change can case trouble if you use explicity types during definition for type safety, as in:: ... (destructor)Example_dealloc, /* tp_dealloc */ (printfunc)0, /* tp_print */ (getattrfunc)0, /* tp_getattr */ (setattrfunc)0, /* tp_setattr */ (cmpfunc)0, /* tp_compare */ ... In this case, make an exception for tp_compare, and use just ``NULL``. Python 3 also adds new fields at the end of PyTypeObject – but that should not affect initialization. .. index:: double: Porting; PyNumberMethods PyNumberMethods =============== The ``PyNumberMethods`` structure, used to implement number-like behavior and operators, was changed. (Docs: :c:type:`py2 `, :c:type:`py3 `) Specifically, several members were removed: * ``nb_divide`` (Python3 calls ``nb_floor_divide`` or ``nb_true_divide``) * ``nb_coerce`` * ``nb_oct`` * ``nb_hex`` * ``nb_inplace_divide`` (see nb_divide) one was renamed: * ``nb_nonzero`` became ``nb_bool`` and one was blanked: * ``unaryfunc nb_long`` became ``void *nb_reserved`` and must be NULL. The mix of removal strategies on the CPython side makes the port somewhat annoying. As of yet, the py3c library does not provide helpers for porting PyNumberMethods. More investigation is needed to be sure all projects' needs are addressed. What you need to do depends on your initialization style: CPython style ............. This style, used in CPython, works in both old C and C++:: static PyNumberMethods long_as_number = { (binaryfunc)long_add, /*nb_add*/ (binaryfunc)long_sub, /*nb_subtract*/ (binaryfunc)long_mul, /*nb_multiply*/ (binaryfunc)long_div, /*nb_divide*/ long_mod, /*nb_remainder*/ long_divmod, /*nb_divmod*/ long_pow, /*nb_power*/ (unaryfunc)long_neg, /*nb_negative*/ ... When using this, wrap the removed elements in ``#if !IS IS_PY3``. If you use nb_long in Python 2, conditionally set it to NULL in Python 3. Make sure ``nb_int`` is set. C99 style ......... If you don't support both C89 and C++ (!) compilers, you may use the named member initialization feature of C99:: static PyNumberMethods long_as_number = { .tp_add = long_add, .tp_div = long_div, ... If this is the case, lump the non-NULL Python2-only members and ``nb_long`` together in a single ``#if !IS IS_PY3`` block. You will need another ``#if``/``#else`` block to handle to handle both names of ``nb_nonzero``, if using that. .. index:: double: Porting; PyBufferProcs PyBufferProcs ============= The buffer protocol changed significantly in Python 3. Kindly read the :ref:`documentation `, and implement the new buffer protocol for Python 3. If you find an easier way to port buffer-aware objects, which other projects could benefit from, remember that py3c welcomes contributions. py3c-1.0/doc/source/fileshim.rst000066400000000000000000000024411323632703100166300ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Licensed under CC-BY-SA-3.0; see the license file .. highlight:: c .. index:: double: Porting; PyFile The PyFile API ============== In Python 3, the PyFile API was reduced to a few functions, and is now meant for internal interpreter use. Python files (and file-like objects) should be manipulated with the API defined by the :py:mod:`py3:io` module. But, in the real world, some C libraries only provide debugging output to ``FILE*``. For cases like this, py3c provides a quick-and-dirty replacement for :c:func:`py2:PyFile_AsFile`: .. c:function:: FILE* py3c_PyFile_AsFileWithMode(PyObject *py_file, const char *mode) Open a (file-backed) Python file object as ``FILE*``. :param py_file: The file object, which must have a working ``fileno()`` method :param mode: A mode appropriate for ``fdopen``, such as ``'r'`` or ``'w'`` This function presents several caveats: * Only works on file-like objects backed by an actual file * All C-level writes should be done before additional Python-level writes are allowed (e.g. by running Python code). * Though the function tries to flush, due to different layers of buffering there is no guarantee that reads and writes will be ordered correctly. py3c-1.0/doc/source/guide-cleanup.rst000066400000000000000000000040711323632703100175530ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Licensed under CC-BY-SA-3.0; see the license file .. highlight:: c .. index:: single: Cleanup Cleanup – Dropping Support for Python 2 ======================================= When users of your C extension are not using Python 2 any more, or you need to use one of Python 3's irresistible new features, you can convert the project to use Python 3 only. As mentioned earlier, it is usually not a good idea to do this until you have full support for both Pythons. With py3c, dropping Python 2 basically amounts to expanding all its compat macros. In other words, remove the ``py3c.h`` header, and fix the compile errors. * .. index:: double: Cleanup; Strings double: Cleanup; Bytes double: Cleanup; Unicode Convert ``PyStr_*`` to ``PyUnicode_*``; ``PyInt_*`` to ``PyLong_*``. * .. index:: double: Cleanup; Module Initialization Instead of ``MODULE_INIT_FUNC()``, write:: PyMODINIT_FUNC PyInit_(void); PyMODINIT_FUNC PyInit_(void) * .. index:: double: Cleanup; Types Remove ``Py_TPFLAGS_HAVE_WEAKREFS`` and ``Py_TPFLAGS_HAVE_ITER`` (py3c defines them as 0). * .. index:: double: Cleanup; Comparisons Replace ``return PY3C_RICHCMP`` by :c:func:`Py_RETURN_RICHCOMPARE`, as mentioned in :c:macro:`PY3C_RICHCMP` documentation. * Replace :c:func:`Py_RETURN_RICHCOMPARE` and :c:func:`Py_UNREACHABLE` by its expansion, unless you either support Python 3.7+ only or keep the ``py3c/comparison.h`` header. * Replace :c:func:`Py_RETURN_NOTIMPLEMENTED` by its expansion, unless you either support Python 3.3+ only or keep the ``py3c/comparison.h`` header. * Drop ``capsulethunk.h``, if you're using it. * Remove any code in ``#if !IS_PY3`` blocks, and the ifs around ``#if IS_PY3`` ones. You will want to check the code as you're doing this. For example, replacing PyLong can easily result in code like ``if (PyInt_Check(o) || PyInt_Check(o))``. Enjoy your Python 3-compatible extension! py3c-1.0/doc/source/guide-modernization.rst000066400000000000000000000106371323632703100210130ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Licensed under CC-BY-SA-3.0; see the license file .. highlight:: c .. index:: single: Modernization Modernization ============= Before porting a C extension to Python 3, you'll need to make sure that you're not using features deprecated even in Python 2. Also, many of Python 3's improvements have been backported to Python 2.6, and using them will make the porting process easier. For all changes you do, be sure add tests to ensure you do not break anything. .. index:: double: Modernization; PyObject structure double: Modernization; Objects PyObject Structure Members ~~~~~~~~~~~~~~~~~~~~~~~~~~ To conform to C's strict aliasing rules, PyObject_HEAD, which provides members such as ``ob_type`` and ``ob_refcnt``, is a separate struct in Python 3. Access to these members is provided by macros, which have been ported to Python 2.6: ============== ============== Instead of use ============== ============== obj->ob_type Py_TYPE(obj) obj->ob_refcnt Py_REFCNT(obj) obj->ob_size Py_SIZE(obj) ============== ============== And for initialization of type objects, the sequence :: PyObject_HEAD_INIT(NULL) 0, /* ob_size */ must be replaced with :: PyVarObject_HEAD_INIT(NULL, 0) .. index:: double: Modernization; Constants Adding module-level constants ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Often, module initialization uses code like this:: PyModule_AddObject(m, "RDWR", PyInt_FromLong(O_RDWR)); PyModule_AddObject(m, "__version__", PyString_FromString("6.28")); Python 2.6 introduced convenience functions, which are shorter to write:: PyModule_AddIntConstant(m, "RDWR", O_RDWR) PyModule_AddStringConstant(m, "__version__", "6.28") These will use native int and str types in both Python versions. .. index:: double: Modernization; Classes New-Style Classes ~~~~~~~~~~~~~~~~~ The `old-style classes `_ (``PyClass_*`` and ``PyInstance_*``) will be removed in Python 3. Instead, use `type objects `_, which have been available since Python 2.2. .. index:: double: Modernization; PyCObject double: Modernization; PyCapsule .. _pycapsule-porting: PyCObject to PyCapsule ~~~~~~~~~~~~~~~~~~~~~~ The `PyCObject API `_ has been removed in Python 3.3. You should instead use its replacement, `PyCapsule `_, which is available in Python 2.7 and 3.1+. For the rationale behind Capsules, see `CPython issue 5630 `_. If you need to support Python 2.6, you can use ``capsulethunk.h``, which implements the PyCapsule API (with some limitations) in terms of PyCObject. For instructions, see the chapter :doc:`capsulethunk`. The port to PyCapsule API should be straightforward: * Instead of :c:func:`PyCObject_FromVoidPtr(obj, destr) `, use :c:func:`PyCapsule_New(obj, name, destr) `. If the capsule will be available as a module attribute, use ``"."`` for *name*. Otherwise, use your best judgment, but try making the name unique. * Instead of :c:func:`PyCObject_FromVoidPtrAndDesc(obj, desc, destr) `, use :c:func:`py3:PyCapsule_New` as above; then call :c:func:`PyCapsule_SetContext(obj, desc) `. * Instead of :c:func:`PyCObject_AsVoidPtr(obj) `, use :c:func:`PyCapsule_GetPointer(obj, name) `. You will need to provide a capsule name, which is checked at runtime as a form of type safety. * Instead of :c:func:`py2:PyCObject_GetDesc`, use :c:func:`py3:PyCapsule_GetContext`. * Instead of :c:func:`py2:PyCObject_SetVoidPtr`, use :c:func:`py3:PyCapsule_SetPointer`. * Change all CObject destructors to :c:type:`PyCapsule destructors `, which take the PyCapsule object as their only argument. .. index:: double: Modernization; Comparisons Comparisons ~~~~~~~~~~~ .. note:: In previous versions, this chapter talked about rich comparison, but those changes are better left to :ref:`porting `. Done! ~~~~~ When your project is sufficiently modernized, and the tests still pass under Python 2, you're ready to start the actual :doc:`Porting `. py3c-1.0/doc/source/guide-porting.rst000066400000000000000000000344151323632703100176130ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Licensed under CC-BY-SA-3.0; see the license file .. highlight:: c .. index:: single: Porting Porting – Adding Support for Python 3 ===================================== After you :doc:`modernize ` your C extension to use the latest features available in Python 2, it is time to address the differences between Python 2 and 3. The recommended way to port is keeping single-source compatibility between Python 2 and 3, until support Python 2 can be safely dropped. For Python code, you can use libraries like `six `_ and `future `_, and, failing that, ``if sys.version_info >= (3, 0):`` blocks for conditional code. For C, the py3c library provides common tools, and for special cases you can use conditional compilation with ``#if IS_PY3``. To start using py3c, ``#include ``, and instruct your compiler to find the header. .. index:: double: Porting; Strings double: Porting; Bytes double: Porting; Unicode The Bytes/Unicode split ~~~~~~~~~~~~~~~~~~~~~~~ The most painful change for extension authors is the bytes/unicode split: unlike Python 2's ``str`` or C's ``char*``, Python 3 introduces a sharp divide between *human-readable strings* and *binary data*. You will need to decide, for each string value you use, which of these two types you want. Make the division as sharp as possible: mixing the types tends to lead to utter chaos. Functions that take both Unicode strings and bytes (in a single Python version) should be rare, and should generally be convenience functions in your interface; not code deep in the internals. However, you can use a concept of **native strings**: a type that corresponds to the ``str`` type in Python: PyBytes on Python 2, and PyUnicode in Python 3. This is the type that you will need to return from functions like ``__str__`` and ``__repr__. Using the **native string** extensively is suitable for conservative projects: it affects the semantics under Python 2 as little as possible, while not requiring the resulting Python 3 API to feel contorted. With py3c, functions for the native string type are PyStr_* (PyStr_FromString, PyStr_Type, PyStr_Check, etc.). They correspond to `PyString `_ on Python 2, and `PyUnicode `_ on Python 3. The supported API is the intersection of `PyString_* `_ and `PyUnicode_* `_, except PyStr_Size (see below) and the deprecated PyUnicode_Encode; additionally `PyStr_AsUTF8String `_ is defined. Keep in mind py3c expects that native strings are always encoded with ``utf-8`` under Python 2. If you use a different encoding, you will need to convert between bytes and text manually. For binary data, use PyBytes_* (PyBytes_FromString, PyBytes_Type, PyBytes_Check, etc.). Python 3.x provides them under these names only; in Python 2.6+ they are aliases of PyString_*. (For even older Pythons, py3c also provides these aliases.) The supported API is the intersection of `PyString_* `_ and `PyBytes_* `_, Porting mostly consists of replacing "``PyString_``" to either "``PyStr_``" or "``PyBytes_``"; just see the caveat about size below. To summarize the four different string type names: ============ ============= ============== =================== String kind py2 py3 Use ============ ============= ============== =================== PyStr_* PyString_* PyUnicode_* Human-readable text PyBytes_* PyString_* ✔ Binary data PyUnicode_* ✔ ✔ Unicode strings PyString_* ✔ error In unported code ============ ============= ============== =================== .. index:: double: Porting; String Size String size ~~~~~~~~~~~ When dealing with Unicode strings, the concept of “size” is tricky, since the number of characters doesn't necessarily correspond to the number of bytes in the string's UTF-8 representation. To prevent subtle errors, this library does *not* provide a PyStr_Size function. Instead, use PyStr_AsUTF8AndSize. This functions like Python 3's `PyUnicode_AsUTF8AndSize `_, except under Python 2, the string is not encoded (as it should already be in UTF-8), the size pointer must not be NULL, and the size may be stored even if an error occurs. .. index:: double: Porting; Ints double: Porting; Long Ints ~~~~ While string type is split in Python 3, the int is just the opposite: ``int`` and ``long`` were unified. ``PyInt_*`` is gone and only ``PyLong_*`` remains (and, to confuse things further, PyLong is named "int" in Python code). The py3c headers alias PyInt to PyLong, so if you're using them, there's no need to change at this point. .. index:: double: Porting; Argument parsing double: Porting; PyArg_Parse double: Porting; Py_BuildValue Floats ~~~~~~ In Python 3, the function :c:func:`PyFloat_FromString ` lost its second, ignored argument. The py3c headers redefine the function to take one argument even in Python 2. You will need to remove the excess argument from all calls. Argument Parsing ~~~~~~~~~~~~~~~~ The format codes for argument-parsing functions of the PyArg_Parse family have changed somewhat. In Python 3, the ``s``, ``z``, ``es``, ``es#`` and ``U`` (plus the new ``C``) codes accept only Unicode strings, while ``c`` and ``S`` only accept bytes. Formats accepting Unicode strings usually encode to char* using UTF-8. Specifically, these are ``s``, ``s*``, ``s#``, ``z``, ``z*``, ``z#``, and also ``es``, ``et``, ``es#``, and ``et#`` when the encoding argument is set to NULL. In Python 2, the default encoding was used instead. There is no variant of ``z`` for bytes, which means htere's no built-in way to accept "bytes or NULL" as a ``char*``. If you need this, write an ``O&`` converter. Python 2 lacks an ``y`` code, which, in Python 3, works on byte objects. The use cases needing ``bytes`` in Python 3 and ``str`` in Python 2 should be rare; if needed, use ``#ifdef IS_PY3`` to select a compatible PyArg_Parse call. .. XXX: Write an O& converter for "z" and "y" XXX: Write/document handling pathnames safely and portably; see PyUnicode_FSConverter/PyUnicode_FSDecoder Compare the `Python 2 `_ and `Python 3 `_ docs for full details. .. index:: double: Porting; Module Initialization Defining Extension Types ~~~~~~~~~~~~~~~~~~~~~~~~ If your module defines extension types, i.e. variables of type ``PyTypeObject`` (and related structures like ``PyNumberMethods`` and ``PyBufferProcs``), you might need to make changes to these definitions. Please read the :doc:`Extension types ` guide for details. A common incompatibility comes from type flags, like :data:`Py_TPFLAGS_HAVE_WEAKREFS` and :data:`Py_TPFLAGS_HAVE_ITER`, which are removed in Python 3 (where the functionality is always present). If you are only using these flags in type definitions, (and *not* for example in :c:func:`PyType_HasFeature`), you can include ```` to define them to zero under Python 3. For more information, read the :ref:`Type flags ` section. Module initialization ~~~~~~~~~~~~~~~~~~~~~ The module creation process was overhauled in Python 3. py3c provides a compatibility wrapper so most of the Python 3 syntax can be used. PyModuleDef and PyModule_Create ------------------------------- Module object creation with py3c is the same as in Python 3. First, create a PyModuleDef structure:: static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, /* m_base */ "spam", /* m_name */ NULL, /* m_doc */ -1, /* m_size */ spam_methods /* m_methods */ }; Then, where a Python 2 module would have :: m = Py_InitModule3("spam", spam_methods, "Python wrapper ..."); use instead :: m = PyModule_Create(&moduledef); For ``m_size``, use -1. (If you are sure the module supports multiple subinterpreters, you can use 0, but this is tricky to achieve portably.) Additional members of the PyModuleDef structure are not accepted under Python 2. See `Python documentation `_ for details on PyModuleDef and PyModule_Create. Module creation entrypoint -------------------------- Instead of the ``void init`` function in Python 2, or a Python3-style ``PyObject *PyInit_`` function, use the MODULE_INIT_FUNC macro to define an initialization function, and return the created module from it:: MODULE_INIT_FUNC(name) { ... m = PyModule_Create(&moduledef); ... if (error) { return NULL; } ... return m; } .. index:: double: Porting; Comparisons .. _comparison-porting: Comparisons ~~~~~~~~~~~ Python 2.1 introduced *rich comparisons* for custom objects, allowing separate behavior for the ``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=`` operators, rather than calling one ``__cmp__`` function and interpreting its result according to the requested operation. (See `PEP 207 `_ for details.) In Python 3, the original ``__cmp__``-based object comparison is removed, so all code needs to switch to rich comparisons. Instead of a :: static int cmp(PyObject *obj1, PyObject *obj2) function in the ``tp_compare`` slot, there is now a :: static PyObject* richcmp(PyObject *obj1, PyObject *obj2, int op) in the ``tp_richcompare`` slot. The ``op`` argument specifies the comparison operation: ``Py_EQ`` (==), ``Py_GT`` (>), ``Py_LE`` (<=), etc. Additionally, Python 3 brings a semantic change. Previously, objects of disparate types were ordered according to type, where the ordering of types was undefined (but consistent across, at least, a single invocation of Python). In Python 3, objects of different types are unorderable. It is usually possible to write a comparison function that works for both versions by returning NotImplemented to explicitly fall back to default behavior. To help writing rich comparisons, Python 3.7+ provides a convenience macro, ``Py_RETURN_RICHCOMPARE``, which returns the right ``PyObject *`` result based on two values orderable by C's comparison operators. With py3c, the macro is available for older versions as well. A typical rich comparison function will look something like this:: static PyObject* mytype_richcmp(PyObject *obj1, PyObject *obj2, int op) { if (mytype_Check(obj2)) { Py_RETURN_RICHCOMPARE(get_data(obj1), get_data(obj2), op); } Py_RETURN_NOTIMPLEMENTED; } where ``get_data`` returns an orderable C value (e.g. a pointer or int), and mytype_Check checks if ``get_data`` is of the correct type (usually via PyObject_TypeCheck). Note that the first argument, obj1, is guaranteed to be of the type the function is defined for. If a "cmp"-style function is provided by the C library, compare its result to 0, e.g. :: Py_RETURN_RICHCOMPARE(mytype_cmp(obj1, obj2), 0, op) The :c:macro:`py3:Py_RETURN_RICHCOMPARE` and :c:macro:`py3:Py_RETURN_NOTIMPLEMENTED` macros are provided in Python 3.3+ and 3.7+, respectively; py3c makes them available to older versions as well. If you need more complicated comparison, use the :c:macro:`py3:Py_UNREACHABLE` macro for unknown operation types (``op``). The macro is was added in Python 3.7+, and py3c backports it. .. note:: The ``tp_richcompare`` slot is inherited in subclasses together with ``tp_hash`` and (in Python 2) ``tp_compare``: iff the subclass doesn't define any of them, all are inherited. This means that if a class is modernized, its subclasses don't have to be, *unless* the subclass manipulates compare/hash slots after class creation (e.g. after the :c:func:`PyType_Ready ` call). .. note:: For backwards compatibility with previous versions of itself, py3c provides the :c:macro:`PY3C_RICHCMP` macro, an early draft of what became ``Py_RETURN_RICHCOMPARE``. The File API ~~~~~~~~~~~~ The :c:type:`PyFile ` API was severely reduced :c:func:`in Python 3 `. The new version is specifically intended for internal error reporting in Python. Native Python file objects are officially no longer backed by ``FILE*``. Use the Python API from the :py:mod:`py3:io` module instead of handling files in C. The Python API supports all kinds of file-like objects, not just built-in files – though, admittedly, it's cumbersome to use from plain C. If you really need to access an API that deals with ``FILE*`` only (e.g. for debugging), see py3c's limited :doc:`file API shim `. Other changes ~~~~~~~~~~~~~ If you find a case where py3c doesn't help, use ``#if IS_PY3`` to include code for only one or the other Python version. And if your think others might have the same problem, consider contributing a macro and docs to py3c! .. index:: Building, ABI tags Building ~~~~~~~~ When building your extension, note that Python 3.2 introduced ABI version tags (`PEP 3149 `_), which can be added to shared library filenames to ensure that the library is loaded with the correct Python version. For example, instead of ``foo.so``, the shared library for the extension module ``foo`` might be named ``foo.cpython-33m.so``. Your buildsystem might generate these for you already, but if you need to modify it, you can get the tags from ``systonfig``:: >>> import sysconfig >>> sysconfig.get_config_var('EXT_SUFFIX') '.cpython-34m.so' >>> sysconfig.get_config_var('SOABI') 'cpython-34m' This is completely optional; the old filenames without ABI tags are still valid. Done! ~~~~~ Do your tests now pass under both Python 2 and 3? (And do you have enough tests?) Then you're done porting! Once you decide to drop compatibility with Python 2, you can move to the :doc:`Cleanup ` section. py3c-1.0/doc/source/guide.rst000066400000000000000000000072661323632703100161370ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Licensed under CC-BY-SA-3.0; see the license file .. highlight:: c ===================================== Porting guide for Python C Extensions ===================================== This guide is written for authors of *C extensions* for Python, who want to make their extension compatible with Python 3. It provides comprehensive, step-by-step porting instructions. Before you start adding Python 3 compatibility to your C extension, consider your options: * .. index:: CFFI If you are writing a wrapper for a C library, take a look at `CFFI `_, a C Foreign Function Interface for Python. This lets you call C from Python 2.6+ and 3.3+, as well as PyPy. A C compiler is required for development, but not for installation. * .. index:: Cython For more complex code, consider `Cython `_, which compiles a Python-like language to C, has great support for interfacing with C libraries, and generates code that works on Python 2.6+ and 3.3+. Using CFFI or Cython will make your code more maintainable in the long run, at the cost of rewriting the entire extension. If that's not an option, you will need to update the extension to use Python 3 APIs. This is where py3c can help. This is an *opinionated* guide to porting. It does not enumerate your options, but rather provides one tried way of doing things. This doesn't mean you can't do things your way – for example, you can cherry-pick the macros you need and put them directly in your files. However, dedicated headers for backwards compatibility will make them easier to find when the time comes to remove them. If you want more details, consult the `"Migrating C extensions" chapter `_ from Lennart Regebro's book "Porting to Python 3", the `C porting guide `_ from Python documentation, and the py3c headers for macros to use. The py3c library lives `at Github `_. See the README for installation instructions. .. toctree:: :hidden: 1. Modernization 2. Porting 3. Cleanup .. rubric:: Overview Porting a C extension to Python 3 involves three phases: 1. :doc:`Modernization `, where the code is migrated to the latest Python 2 features, and tests are added to prevent bugs from creeping in later. After this phase, the project will support Python 2.6+. 2. :doc:`Porting `, where support for Python 3 is introduced, but Python 2 compatibility is kept. After this phase, the project will support Python 2.6+ and 3.3+. 3. :doc:`Cleanup `, where support for Python 2 is removed, and you can start using Python 3-only features. After this phase, the project will support Python 3.3+. The first two phases can be done simultaneously; I separate them here because the porting might require involved discussions/decisions about longer-term strategy, while modernization can be done immediately (as soon as support for Python 2.5 is dropped). But do not let the last two stages overlap, unless the port is trivial enough to be done in a single patch. This way you will have working code at all time. Generally, *libraries*, on which other projects depend, will support both Python 2 and 3 for a longer time, to allow dependent code to make the switch. For libraries, the start of phase 3 might be delayed for many years. On the other hand, *applications* can often switch at once, dropping Python 2 support as soon as the porting is done. Ready? The :doc:`guide-modernization` section is waiting! py3c-1.0/doc/source/index.rst000066400000000000000000000044021323632703100161360ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Licensed under CC-BY-SA-3.0; see the license file py3c: Python 2/3 compatibility layer for C extensions ===================================================== This is *py3c*, a library for easing porting C extensions to Python 3, providing macros for *single-source compatibility* between Python 2.6, 2.7, and 3.3+. It could be described as "the `six `_ for C extensions". Pick the docs you wish to read: * :doc:`Porting guide ` A detailed **walkthrough** for porting to Python 3. Read if you wish to start porting a C extension to Python 3. * :doc:`Cheatsheet ` A **quick reference**, helpful if you're in the middle of porting. Also useful if you find yourself working on a project that someone else is porting, and don't understand what's going on. If you want something to print out a stick on your wall, use this – compared to the other docs, you'll save trees. * :doc:`Definition Summary ` A **table** summarizing how py3c's macros are defined. Convenient if you already know the differences between Python 2 and 3, or before a dive into py3c's internals. Also serves as a summary of where py3c provides the Python 3 API, and where it resorts to inventing its own macros. * :doc:`Reference ` Lists **every macro** py3c defines. The search will point you here when it finds a term. * :ref:`Index ` and :ref:`Search ` Head here if you're looking for something specific. Project info ============ The py3c library is available under the MIT license. This documentation is available under the Creative Commons Attribution-ShareAlike 3.0 Unported license. May they serve you well. The high-level history of py3c is chronicled in the :doc:`Changelog `. If you'd like to contribute code, words, suggestions, bug reports, or anything else, do so at `the Github page `_. For more info, see :doc:`Contributing `. Oh, and you should pronounce "py3c" with a hard "c", if you can manage to do so. .. toctree:: :hidden: guide cheatsheet defs reference special-guides contributing changelog py3c-1.0/doc/source/reference.rst000066400000000000000000000531771323632703100170020ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Licensed under CC-BY-SA-3.0; see the license file ============== py3c reference ============== .. highlight:: c Compatibility Layer =================== :: #include // (included in ) .. c:macro:: IS_PY3 Defined as ``1`` when building for Python 3; ``0`` otherwise. .. index:: PyStr .. _PyStr: PyStr ~~~~~ These functions are the intersection of PyString in Python 2, and PyUnicode in Python 3, with a few helpers thrown it. All follow the Python 3 API, except ``PyStr`` is substituted for ``PyUnicode``. .. c:var:: PyStr_Type A :c:type:`PyTypeObject` instance representing a human-readable string. Exposed in Python as ``str``. | Python 2: :c:data:`PyString_Type ` | Python 3: :c:data:`(provided) ` .. c:function:: int PyStr_Check(PyObject *o) Check that *o* is an instance of :ref:`PyStr` or a subtype. | Python 2: :c:func:`PyString_Check ` | Python 3: :c:func:`PyUnicode_Check ` .. c:function:: int PyStr_CheckExact(PyObject *o) Check that *o* is an instance of :ref:`PyStr`, but not a subtype. | Python 2: :c:func:`PyString_CheckExact ` | Python 3: :c:func:`PyUnicode_CheckExact ` .. c:function:: PyObject* PyStr_FromString(const char *u) Create a :ref:`PyStr` from a UTF-8 encoded null-terminated character buffer. | Python 2: :c:func:`PyString_FromString ` | Python 3: :c:func:`PyUnicode_FromString ` .. c:function:: PyObject* PyStr_FromStringAndSize(const char *u, Py_ssize_t len) Create a :ref:`PyStr` from a UTF-8 encoded character buffer, and corresponding size in bytes. Note that human-readable strings should not contain null bytes; but if the size is known, this is more efficient than :c:func:`PyStr_FromString`. | Python 2: :c:func:`PyString_FromStringAndSize ` | Python 3: :c:func:`PyUnicode_FromStringAndSize ` .. c:function:: PyObject* PyStr_FromFormat(const char *format, ...) Create a :ref:`PyStr` from a C printf-style format string and arguments. Note that formatting directives that were added in Python 3 (``%li``, ``%lli``, ``zi``, ``%A``, ``%U``, ``%V``, ``%S``, ``%R``) will not work in Python 2. | Python 2: :c:func:`PyString_FromFormat ` | Python 3: :c:func:`PyUnicode_FromFormat ` .. c:function:: PyObject* PyStr_FromFormatV(const char *format, va_list vargs) As :c:func:`PyStr_FromFormat`, but takes a ``va_list``. | Python 2: :c:func:`PyString_FromFormatV ` | Python 3: :c:func:`PyUnicode_FromFormatV ` .. c:function:: const char* PyStr_AsString(PyObject *s) Return a null-terminated representation of the contents of *s*. The buffer is owned by *s* and must bot be modified, deallocated, or used after *s* is deallocated. Uses the UTF-8 encoding on Python 3. If given an Unicode string on Python 2, uses Python's default encoding. | Python 2: :c:func:`PyString_AsString ` | Python 3: :c:func:`PyUnicode_AsUTF8 ` (!) .. c:function:: PyObject* PyStr_Concat(PyObject *left, PyObject *right) Concatenates two strings giving a new string. | Python 2: implemented in terms of :c:func:`PyString_Concat ` | Python 3: :c:func:`PyUnicode_Concat ` .. c:function:: PyObject* PyStr_Format(PyObject *format, PyObject *args) Format a string; analogous to the Python expression ``format % args``. The *args* must be a tuple or dict. | Python 2: :c:func:`PyString_Format ` | Python 3: :c:func:`PyUnicode_Format ` .. c:function:: void PyStr_InternInPlace(PyObject **string) Intern *string*, in place. | Python 2: :c:func:`PyString_InternInPlace ` | Python 3: :c:func:`PyUnicode_InternInPlace ` .. c:function:: PyObject* PyStr_InternFromString(const char *v) Create an interned string from a buffer. Combines :c:func:`PyStr_FromString` and :c:func:`PyStr_InternInPlace`. In Python 3, *v* must be UTF-8 encoded. | Python 2: :c:func:`PyString_InternFromString ` | Python 3: :c:func:`PyUnicode_InternFromString ` .. c:function:: PyObject* PyStr_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) Create a new string by decoding *size* bytes from *s*, using the specified *encoding*. | Python 2: :c:func:`PyString_Decode ` | Python 3: :c:func:`PyUnicode_Decode ` .. c:function:: char* PyStr_AsUTF8(PyObject *str) Encode a string using UTF-8 and return the result as a char*. Under Python 3, the result is UTF-8 encoded. | Python 2: :c:func:`PyString_AsString ` | Python 3: :c:func:`PyUnicode_AsUTF8 ` .. c:function:: PyObject* PyStr_AsUTF8String(PyObject *str) Encode a string using UTF-8 and return the result as PyBytes. In Python 2, (where PyStr is bytes in UTF-8 encoding already), this is a no-op. | Python 2: identity | Python 3: :c:func:`PyUnicode_AsUTF8String ` .. c:function:: char *PyStr_AsUTF8AndSize(PyObject *str, Py_ssize_t *size) Return the UTF-8-encoded representation of the string, and set *size* to the number of bytes in this representation. The *size* may not be NULL. In Python 2, the string is assumed to be UTF8-encoded. On error, *size* may or may not be set. | Python 2: (\*size = :c:func:`PyString_Size(str) `, :c:func:`PyString_AsString(str) `) | Python 3: :c:func:`PyUnicode_AsUTF8AndSize ` .. index:: PyBytes .. _PyBytes: PyBytes ~~~~~~~ These functions are the intersection of PyString in Python 2, and PyBytes in Python 3. All follow the Python 3 API. .. c:var:: PyBytes_Type A :c:type:`PyTypeObject` instance representing a string of binary data. Exposed in Python 2 as ``str``, and in Python 3 as ``bytes``. | Python 2: :c:data:`PyString_Type ` | Python 3: :c:data:`(provided) ` .. c:function:: int PyBytes_Check(PyObject *o) Check that *o* is an instance of :ref:`PyBytes` or a subtype. | Python 2: :c:func:`PyString_Check ` | Python 3: :c:func:`(provided) ` .. c:function:: int PyBytes_CheckExact(PyObject *o) Check that *o* is an instance of :ref:`PyBytes`, but not a subtype. | Python 2: :c:func:`PyString_CheckExact ` | Python 3: :c:func:`(provided) ` .. c:function:: PyObject* PyBytes_FromString(const char *v) Create a :ref:`PyBytes` from a NULL-terminated C buffer. Note that binary data might contain null bytes; consider using :c:func:`PyBytes_FromStringAndSize` instead. | Python 2: :c:func:`PyString_FromString ` | Python 3: :c:func:`(provided) ` .. c:function:: PyObject* PPyBytes_FromStringAndSize(const char *v, Py_ssize_t len) Create a :ref:`PyBytes` from a C buffer and size. | Python 2: :c:func:`PyString_FromStringAndSize ` | Python 3: :c:func:`(provided) ` .. c:function:: PyObject* PyBytes_FromFormat(const char *format, ...) Create a :ref:`PyBytes` from a C printf-style format string and arguments. | Python 2: :c:func:`PyString_FromFormat ` | Python 3: :c:func:`(provided) ` .. c:function:: PyObject* PyBytes_FromFormatV(const char *format, va_list args) As :c:func:`PyBytes_FromFormat`, but takes a ``va_list``. | Python 2: :c:func:`PyString_FromFormatV ` | Python 3: :c:func:`(provided) ` .. c:function:: Py_ssize_t PyBytes_Size(PyObject *o) Return the number of bytes in a :ref:`PyBytes` object. | Python 2: :c:func:`PyString_Size ` | Python 3: :c:func:`(provided) ` .. c:function:: Py_ssize_t PyBytes_GET_SIZE(PyObject *o) As :c:func:`PyBytes_Size` but without error checking. | Python 2: :c:func:`PyString_GET_SIZE ` | Python 3: :c:func:`(provided) ` .. c:function:: char *PyBytes_AsString(PyObject *o) Return the buffer in a :ref:`PyBytes` object. The data must not be modifiet or deallocated, or used after a reference to *o* is no longer held. | Python 2: :c:func:`PyString_AsString ` | Python 3: :c:func:`(provided) ` .. c:function:: char *PyBytes_AS_STRING(PyObject *o) As :c:func:`PyBytes_AsString` but without error checking. | Python 2: :c:func:`PyString_AS_STRING ` | Python 3: :c:func:`(provided) ` .. c:function:: int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length) Get the buffer and size stored in a :ref:`PyBytes` object. | Python 2: :c:func:`PyString_AsStringAndSize ` | Python 3: :c:func:`(provided) ` .. c:function:: void PyBytes_Concat(PyObject **bytes, PyObject *newpart) Concatenate *newpart* to *bytes*, returning a new object in *bytes*, and discarding the old. | Python 2: :c:func:`PyString_Concat ` | Python 3: :c:func:`(provided) ` .. c:function:: void PyBytes_ConcatAndDel(PyObject **bytes, PyObject *newpart) As :c:func:`PyBytes_AsString` but decreases reference count of *newpart*. | Python 2: :c:func:`PyString_ConcatAndDel ` | Python 3: :c:func:`(provided) ` .. c:function:: int _PyBytes_Resize(PyObject **string, Py_ssize_t newsize) Used for efficiently build bytes objects; see the Python docs. | Python 2: :c:func:`_PyString_Resize ` | Python 3: :c:func:`(provided) ` .. index:: PyInt .. _PyInt: PyInt ~~~~~ These functions allow extensions to make the diistinction between ints and longs on Python 2. All follow the Python 2 API. .. c:var:: PyInt_Type A :c:type:`PyTypeObject` instance representing an integer that fits in a C long. | Python 2: :c:data:`(provided) ` | Python 3: :c:data:`PyLong_Type ` .. c:function:: int PyInt_Check(PyObject *o) Check that *o* is an instance of :ref:`PyInt` or a subtype. | Python 2: :c:func:`(provided) ` | Python 3: :c:func:`PyLong_Check ` .. c:function:: int PyInt_CheckExact(PyObject *o) Check that *o* is an instance of :ref:`PyInt`, but not a subtype. | Python 2: :c:func:`(provided) ` | Python 3: :c:func:`PyLong_CheckExact ` .. c:function:: PyObject* PyInt_FromString(char *str, char **pend, int base) Convert a string to :ref:`PyInt`. See the Python docs. | Python 2: :c:func:`(provided) ` | Python 3: :c:func:`PyLong_FromString ` .. c:function:: PyObject* PyInt_FromLong(long i) Convert a C long int to :ref:`PyInt`. | Python 2: :c:func:`(provided) ` | Python 3: :c:func:`PyLong_FromLong ` .. c:function:: PyObject* PyInt_FromSsize_t(Py_ssize_t i) Convert a Py_ssize_t int to :ref:`PyInt`. | Python 2: :c:func:`(provided) ` | Python 3: :c:func:`PyLong_FromSsize_t ` .. c:function:: PyObject* PyInt_FromSize_t(Py_size_t i) Convert a Py_size_t int to :ref:`PyInt`. | Python 2: :c:func:`(provided) ` | Python 3: :c:func:`PyLong_FromSize_t ` .. c:function:: long PyInt_AsLong(PyObject *o) Convert a :ref:`PyInt` to a C long. | Python 2: :c:func:`(provided) ` | Python 3: :c:func:`PyLong_AsLong ` .. c:function:: long PyInt_AS_LONG(PyObject *o) As :c:func:`PyInt_AsLong`, but with no error checking. | Python 2: :c:func:`(provided) ` | Python 3: :c:func:`PyLong_AS_LONG ` .. c:function:: unsigned long PyInt_AsUnsignedLongLongMask(PyObject *o) Convert a Python object to int, and return its value as an unsigned long. | Python 2: :c:func:`(provided) ` | Python 3: :c:func:`PyLong_AsUnsignedLongLongMask ` .. c:function:: Py_ssize_t PyInt_AsSsize_t(PyObject *o) Convert a Python object to int, and return its value as a Py_ssize_t. | Python 2: :c:func:`(provided) ` | Python 3: :c:func:`PyLong_AsSsize_t ` PyFloat ~~~~~~~ .. c:function:: PyObject* PyFloat_FromString(PyObject *str) Create a :c:type:`PyFloatObject` object. The signature follows the Python 3 API, even on Python 2. | Python 2: :c:func:`PyFloat_FromString(str, NULL) ` | Python 3: :c:func:`PyFloat_FromString(str) ` Module Initialization ~~~~~~~~~~~~~~~~~~~~~ .. c:function:: MODULE_INIT_FUNC() Use this macro as the header for the module initialization function. Python 2:: static PyObject *PyInit_(void); void init(void); void init(void) { PyInit_(); } static PyObject *PyInit_(void) Python 3:: PyMODINIT_FUNC PyInit_(void); PyMODINIT_FUNC PyInit_(void) .. c:type:: PyModuleDef Python 2: .. c:member:: int m_base Always set this to :c:macro:`PyModuleDef_HEAD_INIT` .. c:member:: char *m_name .. c:member:: char *m_doc .. c:member:: Py_ssize_t m_size Set this to -1. (Or if your module supports :c:func:`subinterpreters `, use 0) .. c:member:: PyMethodDef m_methods Python 3: :c:type:`(provided) ` .. c:macro:: PyModuleDef_HEAD_INIT | Python 2: ``0`` | Python 3: :c:member:`(provided) ` .. c:function:: PyObject* PyModule_Create(PyModuleDef def) | Python 2: :c:func:`Py_InitModule3 `\(def->m_name, def->m_methods, def->m_doc) | Python 3: :c:func:`(provided) ` Comparison Helpers ================== :: #include // (included in ) .. c:macro:: Py_RETURN_NOTIMPLEMENTED Backported from :c:macro:`Python 3.4 ` for older versions. .. c:macro:: Py_UNREACHABLE Use instead of `assert()` or `abort()` in unreachable code, such as handling undefined comparison operations. Backported from :c:macro:`Python 3.7 ` for older versions. .. c:function:: PyObject* PY_RETURN_RICHCOMPARE(val1, val2, int op) Compares two arguments orderable by C comparison operators (such as C ints or floats), and returns :c:data:`Py_True` or :c:data:`Py_False` based on the result, properly increasing the reference count. The third argument specifies the requested operation, as for a :c:member:`rich comparison function `. Backported from :c:macro:`Python 3.7 ` for older versions. .. c:function:: PyObject* PY3C_RICHCMP(val1, val2, int op) .. deprecated:: 1.0 Use :c:func:`PY_RETURN_RICHCOMPARE` instead A helper for rich comparisons that py3c provided before such a helper was, with slightly changed name and semantics, `included in Python itself `_. There are no plans to remove :c:macro:`PY3C_RICHCMP` from py3c, but before *your project* gets rid of py3c, all calls need to switch to what's provided by CPython. To switch, instead of:: return PY3C_RICHCMP(a, b, op) write:: PY_RETURN_RICHCOMPARE(a, b, op) Types ===== :: #include /* (*NOT* included in ) */ .. _tpflags_ref: Removed type flags are defined as ``0`` in Python 3, which is *only* useful in type definitions. In particular, these macros are *not* suitable for :c:func:`PyType_HasFeature` in Python 3. .. c:macro:: Py_TPFLAGS_HAVE_GETCHARBUFFER .. c:macro:: Py_TPFLAGS_HAVE_SEQUENCE_IN .. c:macro:: Py_TPFLAGS_HAVE_INPLACEOPS .. c:macro:: Py_TPFLAGS_CHECKTYPES .. c:macro:: Py_TPFLAGS_HAVE_RICHCOMPARE .. c:macro:: Py_TPFLAGS_HAVE_WEAKREFS .. c:macro:: Py_TPFLAGS_HAVE_ITER .. c:macro:: Py_TPFLAGS_HAVE_CLASS .. c:macro:: Py_TPFLAGS_HAVE_INDEX .. c:macro:: Py_TPFLAGS_HAVE_NEWBUFFER | Python 2: (provided), e.g. :data:`Py_TPFLAGS_HAVE_WEAKREFS ` | Python 3: ``0`` .. _capsulethunk: Capsules ======== :: #include // (*NOT* included in ) This file provides a PyCapsule API compatibility layer for Python 2.6. Capsules are simulated in terms of PyCObject. The :doc:`capsulethunk` chapter lists the limitations of this solution. .. c:macro:: PyCapsule_Type | Python 2.6: :c:type:`PyCObject_Type ` | 2.7 and 3.x: :c:type:`(provided) ` .. c:macro:: PyCapsule_CheckExact(PyObject *p) | Python 2.6: :c:func:`PyCObject_Check ` | 2.7 and 3.x: :c:func:`(provided) ` .. c:macro:: PyCapsule_IsValid(PyObject *capsule, const char *name) | Python 2.6: :c:func:`PyCObject_Check(capsule) ` | 2.7 and 3.x: :c:func:`(provided) ` .. c:macro:: PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor) | Python 2.6: :c:func:`PyCObject_FromVoidPtr(pointer, destructor) ` | 2.7 and 3.x: :c:func:`(provided) ` .. c:macro:: PyCapsule_GetPointer(PyObject *capsule, const char *name) | Python 2.6: :c:func:`PyCObject_AsVoidPtr(capsule) ` – name is not checked! | 2.7 and 3.x: :c:func:`(provided) ` .. c:macro:: PyCapsule_SetPointer(PyObject *capsule, void *pointer) | Python 2.6: uses CPython internals; effect similar to :c:func:`py2:PyCObject_SetVoidPtr` | 2.7 and 3.x: :c:func:`(provided) ` .. c:macro:: PyCapsule_GetDestructor(PyObject *capsule) | Python 2.6: uses CPython internals to get the a CObject's destructor | 2.7 and 3.x: :c:func:`(provided) ` .. c:macro:: PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor) | Python 2.6: uses CPython internals to replace a CObject's destructor | 2.7 and 3.x: :c:func:`(provided) ` .. c:macro:: PyCapsule_GetName(PyObject *capsule) | Python 2.6: NULL | 2.7 and 3.x: :c:func:`(provided) ` .. c:macro:: PyCapsule_SetName(PyObject *capsule) | Python 2.6: Always raises :py:class:`NotImplementedError` | 2.7 and 3.x: :c:func:`(provided) ` .. c:macro:: PyCapsule_GetContext(PyObject *capsule) | Python 2.6: uses CPython internals to get the CObject "desc" field | 2.7 and 3.x: :c:func:`(provided) ` .. c:macro:: PyCapsule_SetContext(PyObject *capsule, PyCapsule_Destructor destructor) | Python 2.6: uses CPython internals to replace CObject "desc" field | 2.7 and 3.x: :c:func:`(provided) ` .. c:macro:: PyCapsule_Import(const char *name, int no_block) | Python 2.6: backported | 2.7 and 3.x: :c:func:`(provided) ` .. _fileshim: Files ===== :: #include // (*NOT* included in ) .. c:function:: py3c_PyFile_AsFileWithMode(PyObject *py_file, const char *mode) Quick-and-dirty substitute for the removed :c:func:`py2:PyFile_AsFile`. Read the :doc:`file shim ` chapter before using. Shims for New Conveniences in Python 3.4+ ========================================= :: #include // (included in ) Raw Memory Allocation ~~~~~~~~~~~~~~~~~~~~~ Python 3.4 adds several functions to manage “raw” memory in a way that the Python allocator is aware of it. These are safe replacements for stdlib's ``malloc``, ``realloc`` and ``free``. For convenience, ``py3c`` provides backports of these to earlier Python versions. The backports provided here simply use the C standard library functions, except they return unique pointers when zero bytes are requested. .. c:function:: PyMem_RawMalloc(size_t n) Backport of :c:func:`py3:PyMem_RawMalloc`. Replacement for ``malloc``. .. c:function:: PyMem_RawRealloc(void* ptr, size_t n) Backport of :c:func:`py3:PyMem_RawRealloc`. Replacement for ``realloc``. .. c:function:: PyMem_RawFree(void* ptr) Backport of :c:func:`py3:PyMem_Free`. Replacement for ``free``. .. c:function:: PyMem_RawCalloc(size_t n, size_t s) Backport of :c:func:`py3:PyMem_Calloc` from Python 3.5+. Replacement for ``calloc``. Unused Arguments ~~~~~~~~~~~~~~~~ .. c:macro:: Py_UNUSED(arg) Use this for unused arguments in a function definition to silence compiler warnings, e.g. ``PyObject* func(PyObject *Py_UNUSED(ignored))``. Backport of :c:macro:`py3:Py_UNUSED` from Python 3.4+. py3c-1.0/doc/source/special-guides.rst000066400000000000000000000015561323632703100177340ustar00rootroot00000000000000.. Copyright (c) 2015, Red Hat, Inc. and/or its affiliates Copyright (c) 2001-2015 Python Software Foundation; All Rights Reserved Licensed under CC-BY-SA-3.0; see the license file Special Porting Guides ====================== Some porting notes are mentioned outside the main guide, because they either, affect fewer project, or need more extensive discussion. They are linked from the main porting guide. Here is a list: * :doc:`Extension Types `: Porting definitions of extension types (``PyTypeObject`` and related objects like ``PyNumberMethods``) * :doc:`PyCapsule API for Python 2.6 `: Porting PyCObject while retaining support for Python 2.6 * :doc:`PyFile shim `: Quick-and-dirty helpers for porting away from the removed PyFile API .. toctree:: :hidden: ext-types capsulethunk fileshimpy3c-1.0/include/000077500000000000000000000000001323632703100136535ustar00rootroot00000000000000py3c-1.0/include/py3c.h000066400000000000000000000023611323632703100147040ustar00rootroot00000000000000/* The MIT License (MIT) Copyright (c) 2015, Red Hat, Inc. and/or its affiliates 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. */ #ifndef _PY3COMPAT_H_ #define _PY3COMPAT_H_ #include #include #include #include #endif py3c-1.0/include/py3c/000077500000000000000000000000001323632703100145315ustar00rootroot00000000000000py3c-1.0/include/py3c/capsulethunk.h000066400000000000000000000073011323632703100174110ustar00rootroot00000000000000/* Copyright (c) 2011, Larry Hastings * Copyright (c) 2015, py3c contributors * Licensed under the MIT license; see py3c.h * * (Note: Relicensed from PSF: http://bugs.python.org/issue24937#msg250191 ) */ #ifndef __CAPSULETHUNK_H #define __CAPSULETHUNK_H #if ( (PY_VERSION_HEX < 0x02070000) \ || ((PY_VERSION_HEX >= 0x03000000) \ && (PY_VERSION_HEX < 0x03010000)) ) #define __PyCapsule_GetField(capsule, field, error_value) \ ( PyCapsule_CheckExact(capsule) \ ? (((PyCObject *)capsule)->field) \ : (PyErr_SetString(PyExc_TypeError, "CObject required"), (error_value)) \ ) \ #define __PyCapsule_SetField(capsule, field, value) \ ( PyCapsule_CheckExact(capsule) \ ? (((PyCObject *)capsule)->field = value), 0 \ : (PyErr_SetString(PyExc_TypeError, "CObject required"), 1) \ ) \ #define PyCapsule_Type PyCObject_Type #define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule)) #define PyCapsule_IsValid(capsule, name) (PyCObject_Check(capsule)) #define PyCapsule_New(pointer, name, destructor) \ (PyCObject_FromVoidPtr(pointer, (void (*)(void*)) (destructor))) #define PyCapsule_GetPointer(capsule, name) \ (PyCObject_AsVoidPtr(capsule)) /* Don't call PyCObject_SetPointer here, it fails if there's a destructor */ #define PyCapsule_SetPointer(capsule, pointer) \ __PyCapsule_SetField(capsule, cobject, pointer) #define PyCapsule_GetDestructor(capsule) \ __PyCapsule_GetField(capsule, destructor, (void (*)(void*)) NULL) #define PyCapsule_SetDestructor(capsule, dtor) \ __PyCapsule_SetField(capsule, destructor, (void (*)(void*)) dtor) /* * Sorry, there's simply no place * to store a Capsule "name" in a CObject. */ #define PyCapsule_GetName(capsule) NULL static int PyCapsule_SetName(PyObject *capsule, const char *unused) { unused = unused; PyErr_SetString(PyExc_NotImplementedError, "can't use PyCapsule_SetName with CObjects"); return 1; } #define PyCapsule_GetContext(capsule) \ __PyCapsule_GetField(capsule, desc, (void*) NULL) #define PyCapsule_SetContext(capsule, context) \ __PyCapsule_SetField(capsule, desc, context) static void * PyCapsule_Import(const char *name, int no_block) { PyObject *object = NULL; void *return_value = NULL; char *trace; size_t name_length = (strlen(name) + 1) * sizeof(char); char *name_dup = (char *)PyMem_MALLOC(name_length); if (!name_dup) { return NULL; } memcpy(name_dup, name, name_length); trace = name_dup; while (trace) { char *dot = strchr(trace, '.'); if (dot) { *dot++ = '\0'; } if (object == NULL) { if (no_block) { object = PyImport_ImportModuleNoBlock(trace); } else { object = PyImport_ImportModule(trace); if (!object) { PyErr_Format(PyExc_ImportError, "PyCapsule_Import could not " "import module \"%s\"", trace); } } } else { PyObject *object2 = PyObject_GetAttrString(object, trace); Py_DECREF(object); object = object2; } if (!object) { goto EXIT; } trace = dot; } if (PyCObject_Check(object)) { PyCObject *cobject = (PyCObject *)object; return_value = cobject->cobject; } else { PyErr_Format(PyExc_AttributeError, "PyCapsule_Import \"%s\" is not valid", name); } EXIT: Py_XDECREF(object); if (name_dup) { PyMem_FREE(name_dup); } return return_value; } #endif /* #if PY_VERSION_HEX < 0x02070000 */ #endif /* __CAPSULETHUNK_H */ py3c-1.0/include/py3c/comparison.h000066400000000000000000000035031323632703100170550ustar00rootroot00000000000000/* Copyright (c) 2015, Red Hat, Inc. and/or its affiliates * Licensed under the MIT license; see py3c.h */ #ifndef _PY3C_COMPARISON_H_ #define _PY3C_COMPARISON_H_ #include /* Rich comparisons */ #ifndef Py_RETURN_NOTIMPLEMENTED #define Py_RETURN_NOTIMPLEMENTED \ return Py_INCREF(Py_NotImplemented), Py_NotImplemented #endif #ifndef Py_UNREACHABLE #define Py_UNREACHABLE() abort() #endif #ifndef Py_RETURN_RICHCOMPARE #define Py_RETURN_RICHCOMPARE(val1, val2, op) \ do { \ switch (op) { \ case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ default: \ Py_UNREACHABLE(); \ } \ } while (0) #endif #define PY3C_RICHCMP(val1, val2, op) \ ((op) == Py_EQ) ? PyBool_FromLong((val1) == (val2)) : \ ((op) == Py_NE) ? PyBool_FromLong((val1) != (val2)) : \ ((op) == Py_LT) ? PyBool_FromLong((val1) < (val2)) : \ ((op) == Py_GT) ? PyBool_FromLong((val1) > (val2)) : \ ((op) == Py_LE) ? PyBool_FromLong((val1) <= (val2)) : \ ((op) == Py_GE) ? PyBool_FromLong((val1) >= (val2)) : \ (Py_INCREF(Py_NotImplemented), Py_NotImplemented) #endif py3c-1.0/include/py3c/compat.h000066400000000000000000000100111323632703100161560ustar00rootroot00000000000000/* Copyright (c) 2015, Red Hat, Inc. and/or its affiliates * Licensed under the MIT license; see py3c.h */ #ifndef _PY3C_COMPAT_H_ #define _PY3C_COMPAT_H_ #include #if PY_MAJOR_VERSION >= 3 /***** Python 3 *****/ #define IS_PY3 1 /* Strings */ #define PyStr_Type PyUnicode_Type #define PyStr_Check PyUnicode_Check #define PyStr_CheckExact PyUnicode_CheckExact #define PyStr_FromString PyUnicode_FromString #define PyStr_FromStringAndSize PyUnicode_FromStringAndSize #define PyStr_FromFormat PyUnicode_FromFormat #define PyStr_FromFormatV PyUnicode_FromFormatV #define PyStr_AsString PyUnicode_AsUTF8 #define PyStr_Concat PyUnicode_Concat #define PyStr_Format PyUnicode_Format #define PyStr_InternInPlace PyUnicode_InternInPlace #define PyStr_InternFromString PyUnicode_InternFromString #define PyStr_Decode PyUnicode_Decode #define PyStr_AsUTF8String PyUnicode_AsUTF8String /* returns PyBytes */ #define PyStr_AsUTF8 PyUnicode_AsUTF8 #define PyStr_AsUTF8AndSize PyUnicode_AsUTF8AndSize /* Ints */ #define PyInt_Type PyLong_Type #define PyInt_Check PyLong_Check #define PyInt_CheckExact PyLong_CheckExact #define PyInt_FromString PyLong_FromString #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyInt_AsSsize_t PyLong_AsSsize_t /* Module init */ #define MODULE_INIT_FUNC(name) \ PyMODINIT_FUNC PyInit_ ## name(void); \ PyMODINIT_FUNC PyInit_ ## name(void) #else /***** Python 2 *****/ #define IS_PY3 0 /* Strings */ #define PyStr_Type PyString_Type #define PyStr_Check PyString_Check #define PyStr_CheckExact PyString_CheckExact #define PyStr_FromString PyString_FromString #define PyStr_FromStringAndSize PyString_FromStringAndSize #define PyStr_FromFormat PyString_FromFormat #define PyStr_FromFormatV PyString_FromFormatV #define PyStr_AsString PyString_AsString #define PyStr_Format PyString_Format #define PyStr_InternInPlace PyString_InternInPlace #define PyStr_InternFromString PyString_InternFromString #define PyStr_Decode PyString_Decode #ifdef __GNUC__ static PyObject *PyStr_Concat(PyObject *left, PyObject *right) __attribute__ ((unused)); #endif static PyObject *PyStr_Concat(PyObject *left, PyObject *right) { PyObject *str = left; Py_INCREF(left); /* reference to old left will be stolen */ PyString_Concat(&str, right); if (str) { return str; } else { return NULL; } } #define PyStr_AsUTF8String(str) (Py_INCREF(str), (str)) #define PyStr_AsUTF8 PyString_AsString #define PyStr_AsUTF8AndSize(pystr, sizeptr) \ ((*sizeptr=PyString_Size(pystr)), PyString_AsString(pystr)) #define PyBytes_Type PyString_Type #define PyBytes_Check PyString_Check #define PyBytes_CheckExact PyString_CheckExact #define PyBytes_FromString PyString_FromString #define PyBytes_FromStringAndSize PyString_FromStringAndSize #define PyBytes_FromFormat PyString_FromFormat #define PyBytes_FromFormatV PyString_FromFormatV #define PyBytes_Size PyString_Size #define PyBytes_GET_SIZE PyString_GET_SIZE #define PyBytes_AsString PyString_AsString #define PyBytes_AS_STRING PyString_AS_STRING #define PyBytes_AsStringAndSize PyString_AsStringAndSize #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #define _PyBytes_Resize _PyString_Resize /* Floats */ #define PyFloat_FromString(str) PyFloat_FromString(str, NULL) /* Module init */ #define PyModuleDef_HEAD_INIT 0 typedef struct PyModuleDef { int m_base; const char* m_name; const char* m_doc; Py_ssize_t m_size; PyMethodDef *m_methods; } PyModuleDef; #define PyModule_Create(def) \ Py_InitModule3((def)->m_name, (def)->m_methods, (def)->m_doc) #define MODULE_INIT_FUNC(name) \ static PyObject *PyInit_ ## name(void); \ PyMODINIT_FUNC init ## name(void); \ PyMODINIT_FUNC init ## name(void) { PyInit_ ## name(); } \ static PyObject *PyInit_ ## name(void) #endif #endif py3c-1.0/include/py3c/fileshim.h000066400000000000000000000021471323632703100165060ustar00rootroot00000000000000/* Copyright (c) 2015, Red Hat, Inc. and/or its affiliates * Licensed under the MIT license; see py3c.h */ #ifndef _PY3C_FILESHIM_H_ #define _PY3C_FILESHIM_H_ #include /* For debugging purposes only. Caveats: * Only works on file-like objects backed by an actual file * All C-level writes should be done before additional Python-level writes are allowed (e.g. by running Python code). * Though the function tries to flush, there is no guarantee that writes will be reordered due to different layers of buffering. */ static char FLUSH[] = "flush"; static char EMPTY_STRING[] = ""; static FILE* py3c_PyFile_AsFileWithMode(PyObject *py_file, const char *mode) { FILE *f; PyObject *ret; int fd; ret = PyObject_CallMethod(py_file, FLUSH, EMPTY_STRING); if (ret == NULL) { return NULL; } Py_DECREF(ret); fd = PyObject_AsFileDescriptor(py_file); if (fd == -1) { return NULL; } f = fdopen(fd, mode); if (f == NULL) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } return f; } #endif /* _PY3C_FILESHIM_H_ */ py3c-1.0/include/py3c/py3shims.h000066400000000000000000000021051323632703100164570ustar00rootroot00000000000000/* Copyright (c) 2016, Red Hat, Inc. and/or its affiliates * Licensed under the MIT license; see py3c.h */ /* * Shims for new functionality from in Python 3.3+ * * See https://docs.python.org/3/c-api/memory.html#raw-memory-interface */ #ifndef _PY3C_RAWMALLOC_H_ #define _PY3C_RAWMALLOC_H_ #include #include /* Py_UNUSED - added in Python 3.4, documneted in 3.7 */ #ifndef Py_UNUSED #ifdef __GNUC__ #define Py_UNUSED(name) _unused_ ## name __attribute__((unused)) #else #define Py_UNUSED(name) _unused_ ## name #endif #endif /* PyMem_Raw{Malloc,Realloc,Free} - added in Python 3.4 */ #if PY_MAJOR_VERSION < 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 4) #define PyMem_RawMalloc(n) malloc((n) || 1) #define PyMem_RawRealloc(p, n) realloc(p, (n) || 1) #define PyMem_RawFree(p) free(p) #endif /* version < 3.4 */ /* PyMem_RawCalloc - added in Python 3.5 */ #if PY_MAJOR_VERSION < 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 5) #define PyMem_RawCalloc(n, s) calloc((n) || 1, (s) || 1) #endif /* version < 3.5 */ #endif /* _PY3C_RAWMALLOC_H_ */ py3c-1.0/include/py3c/tpflags.h000066400000000000000000000036521323632703100163500ustar00rootroot00000000000000/* Copyright (c) 2015, Red Hat, Inc. and/or its affiliates * Licensed under the MIT license; see py3c.h */ /* * WARNING: These flags are only to be used in class definitions. * * Before including this header file, check that you do not use * these flags with with PyType_HasFeature. Example command: * grep -r PyType_HasFeature . * * In Python 3, *all objects* have the features corresponding to removed flags. */ #ifndef _PY3C_TPFLAGS_H_ #define _PY3C_TPFLAGS_H_ #include #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_HAVE_GETCHARBUFFER 0 #define Py_TPFLAGS_HAVE_SEQUENCE_IN 0 #define Py_TPFLAGS_HAVE_INPLACEOPS 0 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_RICHCOMPARE 0 #define Py_TPFLAGS_HAVE_WEAKREFS 0 #define Py_TPFLAGS_HAVE_ITER 0 #define Py_TPFLAGS_HAVE_CLASS 0 /* Py_TPFLAGS_HEAPTYPE is still optional in py3 */ /* Py_TPFLAGS_BASETYPE is still optional in py3 */ /* Py_TPFLAGS_READY is still useful in py3 */ /* Py_TPFLAGS_READYING is still useful in py3 */ /* Py_TPFLAGS_HAVE_GC is still optional in py3 */ /* Py_TPFLAGS_HAVE_STACKLESS_EXTENSION is still optional in py3 */ #define Py_TPFLAGS_HAVE_INDEX 0 /* Py_TPFLAGS_HAVE_VERSION_TAG is still optional in py3 */ /* Py_TPFLAGS_VALID_VERSION_TAG is still optional in py3 */ /* Py_TPFLAGS_IS_ABSTRACT is still optional in py3 */ #define Py_TPFLAGS_HAVE_NEWBUFFER 0 /* Py_TPFLAGS_INT_SUBCLASS is still optional in py3 */ /* Py_TPFLAGS_LONG_SUBCLASS is still optional in py3 */ /* Py_TPFLAGS_LIST_SUBCLASS is still optional in py3 */ /* Py_TPFLAGS_TUPLE_SUBCLASS is still optional in py3 */ /* Py_TPFLAGS_STRING_SUBCLASS is still optional in py3 */ /* Py_TPFLAGS_UNICODE_SUBCLASS is still optional in py3 */ /* Py_TPFLAGS_DICT_SUBCLASS is still optional in py3 */ /* Py_TPFLAGS_BASE_EXC_SUBCLASS is still optional in py3 */ /* Py_TPFLAGS_TYPE_SUBCLASS is still optional in py3 */ /* py 3.4 adds Py_TPFLAGS_HAVE_FINALIZE */ #endif #endif /* _PY3C_TPFLAGS_H_ */ py3c-1.0/py3c.pc.in000066400000000000000000000003751323632703100140440ustar00rootroot00000000000000# Template file for pkg-config includedir=@includedir@ Name: py3c Description: Python 2/3 compatibility layer for C extensions # Requires exactly one of "python" or "python3". #Requires: python #Requires: python3 Version: 1.0 Cflags: -I${includedir} py3c-1.0/setup.cfg000066400000000000000000000000311323632703100140430ustar00rootroot00000000000000[bdist_wheel] universal=1py3c-1.0/setup.py000066400000000000000000000012201323632703100137350ustar00rootroot00000000000000import os import glob from setuptools import setup def find_headers(): path = os.path.join(os.path.dirname(__file__), 'include') for root, dirs, files in os.walk(path): for filename in files: if filename.endswith('.h'): yield os.path.join(root, filename) with open('README.rst') as f: long_description = f.read() setup( name='py3c', version='1.0', description='Python compatibility headers', long_description=long_description, author='Petr Viktorin', author_email='encukou@gmail.com', url='http://py3c.readthedocs.io/', headers=list(find_headers()), platforms='any') py3c-1.0/test/000077500000000000000000000000001323632703100132075ustar00rootroot00000000000000py3c-1.0/test/__main__.py000066400000000000000000000331461323632703100153100ustar00rootroot00000000000000# encoding: UTF-8 import unittest import sys import operator import gc import tempfile import os import shutil import subprocess import test_py3c PY3 = sys.version_info >= (3, 0) PY2 = not PY3 CAPSULE_THUNK = sys.version_info < (2, 7) TEXT_STRING = 'test string ' + 'ẇíťħ ŮŢḞ∞ ☺' TEST_DATA = 'here is some data' if PY3: intern = sys.intern class StringSubclass(str): pass class IntSubclass(int): pass class TestCase(unittest.TestCase): if sys.version_info < (2, 7): def assertIs(self, left, right): self.assertTrue(left is right) class StringChecks(TestCase): def test_type(self): self.assertIs(test_py3c.str_type, str) def test_check(self): self.assertTrue(test_py3c.str_check("abc")) self.assertFalse(test_py3c.str_check(8)) self.assertTrue(test_py3c.str_check(StringSubclass())) self.assertEqual(test_py3c.str_check(b"abc"), PY2) self.assertEqual(test_py3c.str_check(u"abc"), PY3) def test_check_exact(self): self.assertTrue(test_py3c.str_checkexact("abc")) self.assertFalse(test_py3c.str_checkexact(8)) self.assertFalse(test_py3c.str_checkexact(StringSubclass())) self.assertEqual(test_py3c.str_check(b"abc"), PY2) self.assertEqual(test_py3c.str_check(u"abc"), PY3) def test_fromstring(self): self.assertEqual(test_py3c.str_fromstring(), TEXT_STRING) def test_fromstringandsize(self): self.assertEqual(test_py3c.str_fromstringandsize(11), "test string") self.assertEqual(test_py3c.str_fromstringandsize(36), TEXT_STRING) if PY2: self.assertEqual(test_py3c.str_fromstringandsize(13), TEXT_STRING[:13]) else: self.assertRaises(UnicodeDecodeError, test_py3c.str_fromstringandsize, 13) def test_fromformat(self): self.assertEqual(test_py3c.str_fromformat(), "") self.assertEqual(test_py3c.str_fromformatv(), "") def test_asstring(self): self.assertTrue(test_py3c.str_asstring_check(TEXT_STRING)) self.assertFalse(test_py3c.str_asstring_check("---")) self.assertRaises(TypeError, test_py3c.str_asstring_check, 8) def test_concat(self): self.assertEqual(test_py3c.str_concat(TEXT_STRING, "\0abc"), TEXT_STRING + "\0abc") self.assertRaises((TypeError, SystemError), test_py3c.str_concat, 8, "\0abc") def test_format(self): self.assertEqual(test_py3c.str_format("%s %d %.2f", ("a", 1, 3.5)), "a 1 3.50") self.assertRaises(TypeError, test_py3c.str_format, 8) self.assertRaises(TypeError, test_py3c.str_format, "%d", "-") def test_interninplace(self): self.assertEqual(test_py3c.str_interninplace("ab" + "cd"), intern("abcd")) def test_internfromstring(self): self.assertEqual(test_py3c.str_internfromstring(TEXT_STRING), intern(TEXT_STRING)) def test_decode(self): self.assertEqual(test_py3c.str_decode(11, "strict"), "test string") # XXX #self.assertEqual(test_py3c.str_decode(36, "strict"), UTF8_STRING) #self.assertEqual(test_py3c.str_decode(13, "replace"), "test string \N{REPLACEMENT CHARACTER}") def test_asutf8string(self): if PY2: self.assertEqual(test_py3c.str_asutf8string(TEXT_STRING), TEXT_STRING) else: self.assertEqual(test_py3c.str_asutf8string(TEXT_STRING), TEXT_STRING.encode('utf-8')) def test_asutf8(self): self.assertTrue(test_py3c.str_asutf8_check(TEXT_STRING)) self.assertFalse(test_py3c.str_asutf8_check("---")) self.assertRaises(TypeError, test_py3c.str_asutf8_check, 8) def test_asutf8andsize(self): self.assertTrue(test_py3c.str_asutf8andsize_check(TEXT_STRING)) self.assertFalse(test_py3c.str_asutf8andsize_check("---")) self.assertRaises(TypeError, test_py3c.str_asutf8andsize_check, 8) class IntChecks(TestCase): def test_type(self): self.assertIs(test_py3c.int_type, int) def test_check(self): self.assertTrue(test_py3c.int_check(8)) self.assertFalse(test_py3c.int_check("abc")) self.assertTrue(test_py3c.int_check(IntSubclass())) self.assertEqual(test_py3c.int_check(2**1000), PY3) def test_check_exact(self): self.assertTrue(test_py3c.int_checkexact(8)) self.assertFalse(test_py3c.int_checkexact("abc")) self.assertFalse(test_py3c.int_checkexact(IntSubclass())) self.assertEqual(test_py3c.int_checkexact(2**1000), PY3) def test_from(self): self.assertEqual(test_py3c.int_fromstring(), 8) self.assertEqual(test_py3c.int_fromlong(), 8) self.assertEqual(test_py3c.int_fromssize_t(), 8) self.assertEqual(test_py3c.int_fromsize_t(), 8) def test_as(self): self.assertTrue(test_py3c.int_aslong_check(8)) self.assertTrue(test_py3c.int_aslong_macro_check(8)) self.assertTrue(test_py3c.int_asunsignedlonglongmask_check(8)) self.assertTrue(test_py3c.int_asssize_t_check(8)) class FloatChecks(TestCase): def test_fromstring(self): self.assertEqual(test_py3c.float_fromstring('42'), 42.0) self.assertEqual(test_py3c.float_fromstring('-10.5'), -10.5) class ComparisonHelperChecks(TestCase): def test_return_notimplemented(self): self.assertIs(test_py3c.return_notimplemented(), NotImplemented) def test_unreachable(self): proc = subprocess.Popen( [sys.executable, '-c', 'import test_py3c; test_py3c.test_unreachable()'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() self.assertEqual(stdout, b'') self.assertEqual(stderr, b'') self.assertNotEqual(proc.returncode, 0) class ComparisonChecksBase(object): def test_number(self): num = self.cls(3) self.assertEqual(num.value, 3) num.value = 5 self.assertEqual(num.value, 5) def test_number_number_equality(self): three = self.cls(3) three2 = self.cls(3) five = self.cls(5) self.assertEqual(three, three) self.assertEqual(three, three2) self.assertNotEqual(three, five) def test_number_int_equality(self): three = self.cls(3) five = self.cls(5) self.assertEqual(three, 3) self.assertNotEqual(three, 5) def test_all_comparisons(self): three = self.cls(3) three2 = self.cls(3) five = self.cls(5) for op in (operator.eq, operator.ne, operator.gt, operator.lt, operator.ge, operator.le): self.assertEqual(op(three, three), op(3, 3)) self.assertEqual(op(three, three2), op(3, 3)) self.assertEqual(op(three, five), op(3, 5)) self.assertEqual(op(five, three), op(5, 3)) self.assertEqual(op(three, 3), op(3, 3)) self.assertEqual(op(3, three), op(3, 3)) self.assertEqual(op(three, 5), op(3, 5)) self.assertEqual(op(5, three), op(5, 3)) class OldComparisonChecks(TestCase, ComparisonChecksBase): cls = test_py3c.OldNumber class NewComparisonChecks(TestCase, ComparisonChecksBase): cls = test_py3c.NewNumber class CapsuleChecks(TestCase): def tearDown(self): # Ensure that the destructor was called for each capsule gc.collect() self.assertEqual(test_py3c.capsule_get_count(), 0) def test_get_pointer(self): capsule = test_py3c.capsule_new() self.assertTrue(test_py3c.capsule_getpointer_check(capsule)) if not CAPSULE_THUNK: self.assertRaises(ValueError, test_py3c.capsule_getpointer_nullname_check, capsule) def test_get_pointer_nullname(self): capsule = test_py3c.capsule_new_nullname() self.assertTrue(test_py3c.capsule_getpointer_nullname_check(capsule)) if not CAPSULE_THUNK: self.assertRaises(ValueError, test_py3c.capsule_getpointer_check, capsule) def test_get_destructor(self): capsule = test_py3c.capsule_new() self.assertTrue(test_py3c.capsule_getdestructor_check(capsule)) def test_get_context(self): capsule = test_py3c.capsule_new() self.assertEqual(test_py3c.capsule_getcontext(capsule), None) def test_set_context(self): capsule = test_py3c.capsule_new() test_py3c.capsule_setcontext(capsule, TEST_DATA) self.assertEqual(test_py3c.capsule_getcontext(capsule), TEST_DATA) def test_get_name(self): capsule = test_py3c.capsule_new() if CAPSULE_THUNK: self.assertEqual(test_py3c.capsule_getname(capsule), None) else: self.assertEqual(test_py3c.capsule_getname(capsule), "test_capsule") def test_setname(self): capsule = test_py3c.capsule_new() if CAPSULE_THUNK: self.assertRaises(NotImplementedError, test_py3c.capsule_setname, capsule, "other name") else: test_py3c.capsule_setname(capsule, "other name") self.assertEqual(test_py3c.capsule_getname(capsule), "other name") def test_import(self): self.assertTrue(test_py3c.capsule_import_check('test_py3c.capsule')) def test_valid(self): capsule = test_py3c.capsule_new() self.assertTrue(test_py3c.capsule_valid(capsule)) def test_invalid(self): capsule = test_py3c.capsule_new_nullname() self.assertEqual(test_py3c.capsule_valid(capsule), CAPSULE_THUNK) def test_setdestructor(self): capsule = test_py3c.capsule_new() test_py3c.capsule_setdestructor(capsule) del capsule gc.collect() self.assertEqual(test_py3c.capsule_get_count(), 0) def test_setpointer(self): capsule = test_py3c.capsule_new() self.assertTrue(test_py3c.capsule_getpointer_check(capsule)) test_py3c.capsule_setpointer(capsule) self.assertTrue(test_py3c.capsule_getpointer_check_other(capsule)) def test_type(self): capsule = test_py3c.capsule_new() self.assertTrue(test_py3c.capsule_type_check(capsule)) def test_invalid_operations(self): capsule = "not a capsule" if CAPSULE_THUNK: error = TypeError else: error = ValueError self.assertRaises(error, test_py3c.capsule_getpointer_check, capsule) self.assertRaises(error, test_py3c.capsule_getdestructor_check, capsule) self.assertRaises(error, test_py3c.capsule_getcontext, capsule) self.assertFalse(test_py3c.capsule_valid(capsule)) if CAPSULE_THUNK: self.assertEqual(test_py3c.capsule_getname(capsule), None) else: self.assertRaises(error, test_py3c.capsule_getname, capsule) self.assertRaises(error, test_py3c.capsule_setpointer, capsule) self.assertRaises(error, test_py3c.capsule_setdestructor, capsule) self.assertRaises(error, test_py3c.capsule_setcontext, capsule, "") if CAPSULE_THUNK: self.assertRaises(NotImplementedError, test_py3c.capsule_setname, capsule, "") else: self.assertRaises(error, test_py3c.capsule_setname, capsule, "") class FileShimChecks(TestCase): def setUp(self): self.dirname = tempfile.mkdtemp() self.filename = os.path.join(self.dirname, 'f') def tearDown(self): shutil.rmtree(self.dirname) def test_bad_type(self): err = AttributeError, ValueError, SystemError self.assertRaises(err, test_py3c.file_asfilewithmode, 3, "hello") def test_read_write(self): with open(self.filename, 'w') as pyfile: pass with open(self.filename, 'w+') as pyfile: f = test_py3c.file_asfilewithmode(pyfile, 'w+') test_py3c.file_fwrite(f, "hello") test_py3c.file_fseek(f, 0) val = test_py3c.file_fread(f) self.assertEqual(val, "hello") def test_read(self): with open(self.filename, 'w') as pyfile: pyfile.write('hello') with open(self.filename, 'r') as pyfile: f = test_py3c.file_asfilewithmode(pyfile, "r") val = test_py3c.file_fread(f) self.assertEqual(val, "hello") def test_write(self): with open(self.filename, 'w') as pyfile: f = test_py3c.file_asfilewithmode(pyfile, "w") test_py3c.file_fwrite(f, "hello") with open(self.filename, 'r') as pyfile: self.assertEqual(pyfile.read(), 'hello') class RawMallocChecks(TestCase): def test_raw_malloc(self): test_py3c.test_raw_malloc() def test_raw_malloc(self): test_py3c.test_raw_calloc() def test_raw_realloc(self): test_py3c.test_raw_realloc() def test_raw_realloc_null(self): test_py3c.test_raw_realloc_null() def test_raw_malloc_zerosize(self): test_py3c.test_raw_malloc_zerosize() def test_raw_calloc_zero(self): test_py3c.test_raw_malloc_zerosize() def test_raw_realloc_zero(self): test_py3c.test_raw_malloc_zerosize() def main(): try: unittest.main() except SystemExit as e: if e.code != 0: raise if __name__ == '__main__': main() if hasattr(sys, 'gettotalrefcount'): # For debug builds of Python, verify we don't leak references RUNS = 10 baseline = None gc.collect() refcounts = [None] * RUNS for i in range(RUNS): main() gc.collect() refcounts[i] = sys.gettotalrefcount() # refleak == total refcounts change with every test run if len(set(refcounts)) <= len(refcounts): print('Reference counts are stable') else: print(refcounts) print('Reference counts are not stable') exit('FAIL') py3c-1.0/test/setup.py000066400000000000000000000020171323632703100147210ustar00rootroot00000000000000import sys import os from distutils.core import setup, Extension USE_CPP = (os.environ.get('TEST_USE_CPP') == 'yes') # The C/C++ source is the same, but GCC recognizes the language by extension, # so use a symlink named 'test_py3c.cpp' for C++. # (there's also a gcc -x switch, but it needs to go before the filename; # I don't think setuptools allows that) if USE_CPP: sources = ['test_py3c.cpp'] else: sources = ['test_py3c.c'] extra_compile_args = [] extra_compile_args.extend(['-Werror', '-Wall']) if sys.version_info < (2, 7): # XXX: The PyCapsule (2.6) shim tests aren't yet warning-free in GCC extra_compile_args.extend(['-Wno-format']) test_py3c_module = Extension( 'test_py3c', sources=sources, include_dirs=['../include'], extra_compile_args=extra_compile_args, ) test_py3c_module.extra_compile_args=extra_compile_args setup_args = dict( name='test_py3c', version='0.0', description = '', ext_modules = [test_py3c_module] ) if __name__ == '__main__': setup(**setup_args) py3c-1.0/test/test_py3c.c000066400000000000000000000466511323632703100153040ustar00rootroot00000000000000#include #include "structmember.h" #include #include #include #include #define UTF8_STRING "test string \xe1\xba\x87\xc3\xad\xc5\xa5\xc4\xa7 \xc5\xae\xc5\xa2\xe1\xb8\x9e\xe2\x88\x9e \xe2\x98\xba" #define FORMAT_STRING "<%s:%d>" static const char* test_ptr = "here is some data"; static const char* test_ptr2 = "here is some other data"; static int capsule_count = 0; static PyObject *str_check(PyObject *mod, PyObject * o) { return PyBool_FromLong(PyStr_Check(o)); } static PyObject *str_checkexact(PyObject *mod, PyObject * o) { return PyBool_FromLong(PyStr_CheckExact(o)); } /* Note: this also tests that Py_UNUSED works */ static PyObject *str_fromstring(PyObject *mod, PyObject *Py_UNUSED(o)) { return PyStr_FromString(UTF8_STRING); } static PyObject *str_fromstringandsize(PyObject *mod, PyObject * o) { return PyStr_FromStringAndSize(UTF8_STRING, PyInt_AsLong(o)); } static PyObject *str_fromformat(PyObject *mod) { return PyStr_FromFormat(FORMAT_STRING, "abc", 3); } static PyObject *_fromformatv(const char *fmt, ...) { va_list valist; va_start(valist, fmt); return PyStr_FromFormatV(fmt, valist); } static PyObject *str_fromformatv(PyObject *mod) { return _fromformatv(FORMAT_STRING, "abc", 3); } static PyObject *str_asstring_check(PyObject *mod, PyObject * o) { const char *str = PyStr_AsString(o); if (!str) return NULL; return PyBool_FromLong(!strcmp(str, UTF8_STRING)); } static PyObject *str_concat(PyObject *mod, PyObject *args) { PyObject *left, *right; if (!PyArg_ParseTuple(args, "OO", &left, &right)) return NULL; return PyStr_Concat(left, right); } static PyObject *str_format(PyObject *mod, PyObject *args) { PyObject *fmt, *items; if (!PyArg_ParseTuple(args, "OO", &fmt, &items)) return NULL; return PyStr_Format(fmt, items); } static PyObject *str_interninplace(PyObject *mod, PyObject *o) { /* we have a borrowed reference; need to own it */ Py_INCREF(o); PyStr_InternInPlace(&o); return o; } static PyObject *str_internfromstring(PyObject *mod) { return PyStr_InternFromString(UTF8_STRING); } static PyObject *str_decode(PyObject *mod, PyObject *args) { int size; const char *errors; if (!PyArg_ParseTuple(args, "Is", &size, &errors)) return NULL; return PyStr_Decode(UTF8_STRING, size, "utf-8", errors); } static PyObject *str_asutf8string(PyObject *mod, PyObject *o) { return PyStr_AsUTF8String(o); } static PyObject *str_asutf8_check(PyObject *mod, PyObject * o) { const char *str = PyStr_AsUTF8(o); if (!str) return NULL; return PyBool_FromLong(!strcmp(str, UTF8_STRING)); } static PyObject *str_asutf8andsize_check(PyObject *mod, PyObject * o) { Py_ssize_t size; const char *str = PyStr_AsUTF8AndSize(o, &size); if (!str) return NULL; return PyBool_FromLong(!strcmp(str, UTF8_STRING) && size == 36); } static PyObject *int_check(PyObject *mod, PyObject * o) { return PyBool_FromLong(PyInt_Check(o)); } static PyObject *int_checkexact(PyObject *mod, PyObject * o) { return PyBool_FromLong(PyInt_CheckExact(o)); } static PyObject *int_fromstring(PyObject *mod) { char eight[] = "8"; return PyInt_FromString(eight, NULL, 10); } static PyObject *int_fromlong(PyObject *mod) { return PyInt_FromLong(8); } static PyObject *int_fromssize_t(PyObject *mod) { return PyInt_FromSsize_t((Py_ssize_t)8); } static PyObject *int_fromsize_t(PyObject *mod) { return PyInt_FromSize_t((size_t)8); } static PyObject *int_aslong_check(PyObject *mod, PyObject * o) { return PyBool_FromLong(PyInt_AsLong(o) == 8); } static PyObject *int_aslong_macro_check(PyObject *mod, PyObject * o) { return PyBool_FromLong(PyInt_AS_LONG(o) == 8); } static PyObject *int_asunsignedlonglongmask_check(PyObject *mod, PyObject * o) { return PyBool_FromLong(PyInt_AsUnsignedLongLongMask(o) == 8); } static PyObject *int_asssize_t_check(PyObject *mod, PyObject * o) { return PyBool_FromLong(PyInt_AsSsize_t(o) == 8); } static PyObject *float_fromstring(PyObject *mod, PyObject *o) { return PyFloat_FromString(o); } static PyObject *return_notimplemented(PyObject *mod) { Py_RETURN_NOTIMPLEMENTED; } static PyObject *capsule_get_count(PyObject *mod) { return PyInt_FromLong(capsule_count); } static void capsule_destructor(PyObject *capsule) { const char *name = PyCapsule_GetName(capsule); (void) name; if (!PyErr_Occurred()) { capsule_count--; } else { /* Better way to signal failure? */ capsule_count += 999; } } static void capsule_alternate_destructor(PyObject *capsule) { const char *name = PyCapsule_GetName(capsule); (void) name; if (!PyErr_Occurred()) { capsule_count -= 2; } else { /* Better way to signal failure? */ capsule_count += 999; } } static PyObject *capsule_new(PyObject *mod) { capsule_count++; return PyCapsule_New((void*)test_ptr, "test_capsule", capsule_destructor); } static PyObject *capsule_new_nullname(PyObject *mod) { capsule_count++; return PyCapsule_New((void*)test_ptr, NULL, capsule_destructor); } static PyObject *capsule_getpointer_check(PyObject *mod, PyObject *o) { void * ptr = PyCapsule_GetPointer(o, "test_capsule"); if (ptr == NULL && PyErr_Occurred()) return NULL; return PyBool_FromLong(ptr == test_ptr); } static PyObject *capsule_getpointer_check_other(PyObject *mod, PyObject *o) { void * ptr = PyCapsule_GetPointer(o, "test_capsule"); if (ptr == NULL && PyErr_Occurred()) return NULL; return PyBool_FromLong(ptr == test_ptr2); } static PyObject *capsule_getpointer_nullname_check(PyObject *mod, PyObject *o) { void * ptr = PyCapsule_GetPointer(o, NULL); if (ptr == NULL && PyErr_Occurred()) return NULL; return PyBool_FromLong(ptr == test_ptr); } static PyObject *capsule_getdestructor_check(PyObject *mod, PyObject *o) { void * ptr = (void*) PyCapsule_GetDestructor(o); if (ptr == NULL && PyErr_Occurred()) return NULL; return PyBool_FromLong(ptr == capsule_destructor); } static PyObject *capsule_getcontext(PyObject *mod, PyObject *o) { void * ptr = (void*) PyCapsule_GetContext(o); if (ptr == NULL && PyErr_Occurred()) return NULL; if (ptr == NULL) Py_RETURN_NONE; return PyStr_FromString((char*) ptr); } static PyObject *capsule_setcontext(PyObject *mod, PyObject *args) { PyObject *o; int ret; const char *ptr; if (!PyArg_ParseTuple(args, "Os", &o, &ptr)) return NULL; ret = PyCapsule_SetContext(o, (void*)ptr); if (ret) return NULL; Py_RETURN_NONE; } static PyObject *capsule_getname(PyObject *mod, PyObject *o) { const char* ptr = PyCapsule_GetName(o); if (ptr == NULL && PyErr_Occurred()) return NULL; if (ptr == NULL) Py_RETURN_NONE; return PyStr_FromString(ptr); } static PyObject *capsule_valid(PyObject *mod, PyObject *o) { return PyBool_FromLong(PyCapsule_IsValid(o, "test_capsule")); } static PyObject *capsule_setdestructor(PyObject *mod, PyObject *o) { int ret = PyCapsule_SetDestructor(o, capsule_alternate_destructor); if (ret) return NULL; capsule_count ++; Py_RETURN_NONE; } static PyObject *capsule_setname(PyObject *mod, PyObject *args) { PyObject *o; int ret; const char *ptr; if (!PyArg_ParseTuple(args, "Os", &o, &ptr)) return NULL; ret = PyCapsule_SetName(o, ptr); if (ret) return NULL; Py_RETURN_NONE; } static PyObject *capsule_setpointer(PyObject *mod, PyObject *o) { int ret = PyCapsule_SetPointer(o, (void*)test_ptr2); if (ret) return NULL; Py_RETURN_NONE; } static PyObject *capsule_import_check(PyObject *mod, PyObject *args) { const char *name; void *ptr; if (!PyArg_ParseTuple(args, "s", &name)) return NULL; ptr = PyCapsule_Import(name, 0); if (ptr == NULL && PyErr_Occurred()) return NULL; return PyBool_FromLong(ptr == test_ptr2); } static PyObject *capsule_type_check(PyObject *mod, PyObject *o) { return PyBool_FromLong(PyObject_TypeCheck(o, &PyCapsule_Type)); } static PyObject *file_asfilewithmode(PyObject *mod, PyObject *args) { PyObject *o; const char *mode; FILE *f; if (!PyArg_ParseTuple(args, "Os", &o, &mode)) return NULL; f = py3c_PyFile_AsFileWithMode(o, mode); if (!f) return NULL; return PyCapsule_New(f, "test_py3c._file", NULL); } static PyObject *file_fread(PyObject *mod, PyObject *o) { char data[200]; size_t size; FILE *f = (FILE*) PyCapsule_GetPointer(o, "test_py3c._file"); if (!f) return NULL; size = fread(data, 1, 200, f); if (size > 199) { return PyErr_Format(PyExc_AssertionError, "size read is too big (%zu)", size); } return PyStr_FromStringAndSize(data, size); } static PyObject *file_fwrite(PyObject *mod, PyObject *args) { PyObject *o; Py_buffer pybuf; size_t size_written; FILE *f; if (!PyArg_ParseTuple(args, "Os*", &o, &pybuf)) return NULL; f = (FILE*) PyCapsule_GetPointer(o, "test_py3c._file"); if (!f) { PyBuffer_Release(&pybuf); return NULL; } size_written = fwrite(pybuf.buf, 1, pybuf.len, f); if (size_written != (size_t)pybuf.len) { PyBuffer_Release(&pybuf); return PyErr_Format(PyExc_AssertionError, "size written (%zu) != size of string (%zd)", size_written, pybuf.len); } fflush(f); PyBuffer_Release(&pybuf); Py_RETURN_NONE; } static PyObject *file_fseek(PyObject *mod, PyObject *args) { PyObject *o; size_t pos = 0; FILE *f; int ret; if (!PyArg_ParseTuple(args, "Oi", &o, &pos)) return NULL; f = (FILE*) PyCapsule_GetPointer(o, "test_py3c._file"); if (!f) return NULL; ret = fseek(f, pos, SEEK_SET); if (ret < 0) return PyErr_SetFromErrno(PyExc_OSError); Py_RETURN_NONE; } static PyObject *test_raw_malloc(PyObject *mod, PyObject *args) { char *buf = (char*)PyMem_RawMalloc(1); buf[0] = 'a'; PyMem_RawFree(buf); Py_RETURN_NONE; } static PyObject *test_raw_calloc(PyObject *mod, PyObject *args) { char *buf = (char*)PyMem_RawCalloc(1, 1); buf[0] = 'a'; PyMem_RawFree(buf); Py_RETURN_NONE; } static PyObject *test_raw_realloc(PyObject *mod, PyObject *args) { char *buf = (char*)PyMem_RawMalloc(1); buf[0] = 'a'; buf = (char*)PyMem_RawRealloc(buf, 2); if (buf[0] != 'a') { return PyErr_Format(PyExc_AssertionError, "memory not preserved in PyMem_RawRealloc"); } PyMem_RawFree(buf); Py_RETURN_NONE; } static PyObject *test_raw_realloc_null(PyObject *mod, PyObject *args) { char *buf = (char*)PyMem_RawRealloc(NULL, 2); buf[0] = 'a'; PyMem_RawFree(buf); Py_RETURN_NONE; } static PyObject *test_raw_malloc_zerosize(PyObject *mod, PyObject *args) { char *buf = (char*)PyMem_RawMalloc(0); if (buf == NULL) { return PyErr_Format(PyExc_AssertionError, "PyMem_RawMalloc(0) returned NULL"); } PyMem_RawFree(buf); Py_RETURN_NONE; } static PyObject *test_raw_calloc_zerosize(PyObject *mod, PyObject *args) { char *buf = (char*)PyMem_RawCalloc(0, 0); if (buf == NULL) { return PyErr_Format(PyExc_AssertionError, "PyMem_RawCalloc(0) returned NULL"); } PyMem_RawFree(buf); Py_RETURN_NONE; } static PyObject *test_raw_realloc_zerosize(PyObject *mod, PyObject *args) { char *buf = (char*)PyMem_RawMalloc(1); buf = (char*)PyMem_RawRealloc(buf, 0); if (buf == NULL) { return PyErr_Format(PyExc_AssertionError, "PyMem_RawRealloc(0) returned NULL"); } PyMem_RawFree(buf); Py_RETURN_NONE; } static PyObject *test_unreachable(PyObject *mod) { Py_UNREACHABLE(); } #define FUNC(style, name) { #name, (PyCFunction)name, style, NULL } static PyMethodDef methods[] = { FUNC(METH_O, str_check), FUNC(METH_O, str_checkexact), FUNC(METH_VARARGS, str_fromstring), FUNC(METH_O, str_fromstringandsize), FUNC(METH_NOARGS, str_fromformat), FUNC(METH_NOARGS, str_fromformatv), FUNC(METH_O, str_asstring_check), FUNC(METH_VARARGS, str_concat), FUNC(METH_VARARGS, str_format), FUNC(METH_O, str_interninplace), FUNC(METH_O, str_internfromstring), FUNC(METH_VARARGS, str_decode), FUNC(METH_O, str_asutf8string), FUNC(METH_O, str_asutf8_check), FUNC(METH_O, str_asutf8andsize_check), FUNC(METH_O, int_check), FUNC(METH_O, int_checkexact), FUNC(METH_NOARGS, int_fromstring), FUNC(METH_NOARGS, int_fromlong), FUNC(METH_NOARGS, int_fromssize_t), FUNC(METH_NOARGS, int_fromsize_t), FUNC(METH_O, int_aslong_check), FUNC(METH_O, int_aslong_macro_check), FUNC(METH_O, int_asunsignedlonglongmask_check), FUNC(METH_O, int_asssize_t_check), FUNC(METH_O, float_fromstring), FUNC(METH_NOARGS, return_notimplemented), FUNC(METH_NOARGS, test_unreachable), FUNC(METH_NOARGS, capsule_get_count), FUNC(METH_NOARGS, capsule_new), FUNC(METH_NOARGS, capsule_new_nullname), FUNC(METH_O, capsule_getpointer_check), FUNC(METH_O, capsule_getpointer_check_other), FUNC(METH_O, capsule_getpointer_nullname_check), FUNC(METH_O, capsule_getdestructor_check), FUNC(METH_O, capsule_getcontext), FUNC(METH_VARARGS, capsule_setcontext), FUNC(METH_O, capsule_getname), FUNC(METH_O, capsule_valid), FUNC(METH_O, capsule_setdestructor), FUNC(METH_VARARGS, capsule_setname), FUNC(METH_O, capsule_setpointer), FUNC(METH_VARARGS, capsule_import_check), FUNC(METH_O, capsule_type_check), FUNC(METH_VARARGS, file_asfilewithmode), FUNC(METH_O, file_fread), FUNC(METH_VARARGS, file_fwrite), FUNC(METH_VARARGS, file_fseek), FUNC(METH_VARARGS, test_raw_malloc), FUNC(METH_VARARGS, test_raw_calloc), FUNC(METH_VARARGS, test_raw_realloc), FUNC(METH_VARARGS, test_raw_realloc_null), FUNC(METH_VARARGS, test_raw_malloc_zerosize), FUNC(METH_VARARGS, test_raw_calloc_zerosize), FUNC(METH_VARARGS, test_raw_realloc_zerosize), { NULL } }; /* C++ apparently doesn't allow forward declarations for data * http://stackoverflow.com/a/936589/99057 */ #ifdef __cplusplus #define FORWARD_TYPE extern #else #define FORWARD_TYPE static #endif FORWARD_TYPE PyTypeObject test_py3c_OldNumberType; FORWARD_TYPE PyTypeObject test_py3c_NewNumberType; typedef struct { PyObject_HEAD int number; } test_py3c_Number; static char value_name[] = "value"; static char value_doc[] = "the value as an int"; static PyMemberDef Number_members[] = { {value_name, T_INT, offsetof(test_py3c_Number, number), 0, value_doc}, {NULL} }; static int Number_init(test_py3c_Number *self, PyObject *args, PyObject *kwds) { static char num[] = "num"; static char *kwlist[] = {num, NULL}; if (! PyArg_ParseTupleAndKeywords(args, kwds, "i", kwlist, &self->number)) return -1; return 0; } static PyObject* Number_py3c_richcmp(PyObject *obj1, PyObject *obj2, int op) { test_py3c_Number *self = (test_py3c_Number *)obj1; if (PyObject_TypeCheck(obj2, &test_py3c_OldNumberType)) { test_py3c_Number *other = (test_py3c_Number *)obj2; return PY3C_RICHCMP(self->number, other->number, op); } if (PyInt_Check(obj2)) { return PY3C_RICHCMP(self->number, PyInt_AsLong(obj2), op); } Py_RETURN_NOTIMPLEMENTED; } static PyObject* Number_py_richcmp(PyObject *obj1, PyObject *obj2, int op) { test_py3c_Number *self = (test_py3c_Number *)obj1; if (PyObject_TypeCheck(obj2, &test_py3c_NewNumberType)) { test_py3c_Number *other = (test_py3c_Number *)obj2; Py_RETURN_RICHCOMPARE(self->number, other->number, op); } if (PyInt_Check(obj2)) { Py_RETURN_RICHCOMPARE(self->number, PyInt_AsLong(obj2), op); } Py_RETURN_NOTIMPLEMENTED; } #ifndef __cplusplus static #endif PyTypeObject test_py3c_OldNumberType = { PyVarObject_HEAD_INIT(NULL, 0) "test_py3c.OldNumber", /*tp_name*/ sizeof(test_py3c_Number), /*tp_basicsize*/ 0, /*tp_itemsize*/ 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "A mutable object that stores an int. Uses PY3C_RICHCMP for comparisons.", 0, /* tp_traverse */ 0, /* tp_clear */ Number_py3c_richcmp, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ Number_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Number_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; #ifndef __cplusplus static #endif PyTypeObject test_py3c_NewNumberType = { PyVarObject_HEAD_INIT(NULL, 0) "test_py3c.NewNumber", /*tp_name*/ sizeof(test_py3c_Number), /*tp_basicsize*/ 0, /*tp_itemsize*/ 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "A mutable object that stores an int. Uses PY_RETURN_RICHCOMPARE for comparisons.", 0, /* tp_traverse */ 0, /* tp_clear */ Number_py_richcmp, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ Number_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Number_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "test_py3c", /* m_name */ PyDoc_STR("Testing module for py3c."), /* m_doc */ -1, /* m_size */ methods, /* m_methods */ }; #ifdef __cplusplus extern "C" { #endif MODULE_INIT_FUNC(test_py3c) { PyObject *capsule = NULL; PyObject *m = NULL; if (PyType_Ready(&test_py3c_OldNumberType) < 0) goto error; if (PyType_Ready(&test_py3c_NewNumberType) < 0) goto error; capsule = PyCapsule_New((void*)test_ptr2, "test_py3c.capsule", NULL); if (capsule == NULL) goto error; m = PyModule_Create(&moduledef); if (PyModule_AddObject(m, "str_type", (PyObject *)&PyStr_Type)) goto error; Py_INCREF(&PyStr_Type); if (PyModule_AddObject(m, "int_type", (PyObject *)&PyInt_Type)) goto error; Py_INCREF(&PyInt_Type); Py_INCREF(&test_py3c_OldNumberType); if (PyModule_AddObject(m, "OldNumber", (PyObject *)&test_py3c_OldNumberType)) goto error; Py_INCREF(&test_py3c_NewNumberType); if (PyModule_AddObject(m, "NewNumber", (PyObject *)&test_py3c_NewNumberType)) goto error; if (PyModule_AddObject(m, "capsule", capsule)) goto error; return m; error: Py_XDECREF(capsule); return NULL; } #ifdef __cplusplus } #endif py3c-1.0/test/test_py3c.cpp000077700000000000000000000000001323632703100177042test_py3c.custar00rootroot00000000000000