Dataset Viewer
Auto-converted to Parquet
file_name
stringlengths
6
169
content
stringlengths
52
102k
#psf-events.txt
Python Software Foundation Code of Conduct The Python community is made up of members from around the globe with a diverse set of skills, personalities, and experiences. It is through these differences that our community experiences great successes and continued growth. When you're working with members of the community, this Code of Conduct will help steer your interactions and keep Python a positive, successful, and growing community. Our Community Members of the Python community are open, considerate, and respectful . Behaviours that reinforce these values contribute to a positive environment, and include: Being open. Members of the community are open to collaboration, whether it's on PEPs, patches, problems, or otherwise. Focusing on what is best for the community. We're respectful of the processes set forth in the community, and we work within them. Acknowledging time and effort. We're respectful of the volunteer efforts that permeate the Python community. We're thoughtful when addressing the efforts of others, keeping in mind that often times the labor was completed simply for the good of the community. Being respectful of differing viewpoints and experiences. We're receptive to constructive comments and criticism, as the experiences and skill sets of other members contribute to the whole of our efforts. Showing empathy towards other community members. We're attentive in our communications, whether in person or online, and we're tactful when approaching differing views. Being considerate. Members of the community are considerate of their peers -- other Python users. Being respectful. We're respectful of others, their positions, their skills, their commitments, and their efforts. Gracefully accepting constructive criticism. When we disagree, we are courteous in raising our issues. Using welcoming and inclusive language. We're accepting of all who wish to take part in our activities, fostering an environment where anyone can participate and everyone can make a difference. Our Standards Every member of our community has the right to have their identity respected. The Python community is dedicated to providing a positive experience for everyone, regardless of age, gender identity and expression, sexual orientation, disability, physical appearance, body size, ethnicity, nationality, race, or religion (or lack thereof), education, or socio-economic status. Inappropriate Behavior Examples of unacceptable behavior by participants include: Harassment of any participants in any form Deliberate intimidation, stalking, or following Logging or taking screenshots of online activity for harassment purposes Publishing others' private information, such as a physical or electronic address, without explicit permission Violent threats or language directed against another person Incitement of violence or harassment towards any individual, including encouraging a person to commit suicide or to engage in self-harm Creating additional online accounts in order to harass another person or circumvent a ban Sexual language and imagery in online communities or in any conference venue, including talks Insults, put downs, or jokes that are based upon stereotypes, that are exclusionary, or that hold others up for ridicule Excessive swearing Unwelcome sexual attention or advances Unwelcome physical contact, including simulated physical contact (eg, textual descriptions like "hug" or "backrub") without consent or after a request to stop Pattern of inappropriate social contact, such as requesting/assuming inappropriate levels of intimacy with others Sustained disruption of online community discussions, in-person presentations, or other in-person events Continued one-on-one communication after requests to cease Other conduct that is inappropriate for a professional audience including people of many different backgrounds Community members asked to stop any inappropriate behavior are expected to comply immediately. Weapons Policy No weapons are allowed at Python Software Foundation events. Weapons include but are not limited to explosives (including fireworks), guns, and large knives such as those used for hunting or display, as well as any other item used for the purpose of causing injury or harm to others. Anyone seen in possession of one of these items will be asked to leave immediately, and will only be allowed to return without the weapon. Consequences If a participant engages in behavior that violates this code of conduct, the Python community Code of Conduct team may take any action they deem appropriate, including warning the offender or expulsion from the community and community events with no refund of event tickets. The full list of consequences for inappropriate behavior is listed in the Enforcement Procedures . Thank you for helping make this a welcoming, friendly community for everyone. Scope PSF Events This Code of Conduct applies to the following people at events hosted by the Python Software Foundation, and events hosted by projects under the PSF's fiscal sponsorship : staff Python Software Foundation board members speakers panelists tutorial or workshop leaders poster presenters people invited to meetings or summits exhibitors organizers volunteers all attendees The Code of Conduct applies in official venue event spaces, including: exhibit hall or vendor tabling area panel and presentation rooms hackathon or sprint rooms tutorial or workshop rooms poster session rooms summit or meeting rooms staff areas con suite meal areas party suites walkways, hallways, elevators, and stairs that connect any of the above spaces The Code of Conduct applies to interactions with official event accounts on social media spaces and phone applications, including: comments made on official conference phone apps comments made on event video hosting services comments made on the official event hashtag or panel hashtags Event organizers will enforce this code throughout the event. Each event is required to provide a Code of Conduct committee that receives, evaluates, and acts on incident reports. Each event is required to provide contact information for the committee to attendees. The event Code of Conduct committee may (but is not required to) ask for advice from the Python Software Foundation Code of Conduct work group. The Python Software Foundation Code of Conduct work group can be reached by emailing conduct-wg@python.org . PSF Online Spaces This Code of Conduct applies to the following online spaces: Mailing lists, including docs , core-mentorship and all other mailing lists hosted on python.org Core developers' Python Discord server The PSF Discord and Slack servers Python Software Foundation hosted Discourse server discuss.python.org Code repositories, issue trackers, and pull requests made against any Python Software Foundation-controlled GitHub organization Any other online space administered by the Python Software Foundation This Code of Conduct applies to the following people in official Python Software Foundation online spaces: PSF Members, including Fellows admins of the online space maintainers reviewers contributors all community members Each online space listed above is required to provide the following information to the Python Software Foundation Code of Conduct work group: contact information for any administrators/moderators Each online space listed above is encouraged to provide the following information to community members: a welcome message with a link to this Code of Conduct and the contact information for making an incident report conduct-wg@python.org The Python Software Foundation Code of Conduct work group will receive and evaluate incident reports from the online communities listed above. The Python Software Foundation Code of Conduct work group will work with online community administrators/moderators to suggest actions to take in response to a report. In cases where the administrators/moderators disagree on the suggested resolution for a report, the Python Software Foundation Code of Conduct work group may choose to notify the Python Software Foundation board. Contact Information If you believe that someone is violating the code of conduct, or have any other concerns, please contact a member of the Python Software Foundation Code of Conduct work group immediately. They can be reached by emailing conduct-wg@python.org Procedure for Handling Incidents Python Software Foundation Community Member Procedure For Reporting Code of Conduct Incidents Python Software Foundation Code of Conduct Working Group Enforcement Procedures License This Code of Conduct is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License . Attributions This Code of Conduct was forked from the example policy from the Geek Feminism wiki, created by the Ada Initiative and other volunteers , which is under a Creative Commons Zero license . Additional new language and modifications were created by Sage Sharp of Otter Tech . Language was incorporated from the following Codes of Conduct: Affect Conf Code of Conduct , licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License . Citizen Code of Conduct , licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License . Contributor Covenant version 1.4 , licensed Creative Commons Attribution 4.0 License . Django Project Code of Conduct , licensed under a Creative Commons Attribution 3.0 Unported License . LGBTQ in Tech Slack Code of Conduct , licensed under a Creative Commons Zero License . PyCon 2018 Code of Conduct , licensed under a Creative Commons Attribution 3.0 Unported License . Rust Code of Conduct July 19, 2024
#rietveld.txt
Title: PEP 512 – Migrating from hg.python.org to GitHub | peps.python.org PEP 512 – Migrating from hg.python.org to GitHub Author : Brett Cannon <brett at python.org> Discussions-To : Core-Workflow list Status : Final Type : Process Created : 17-Jan-2015 Post-History : 17-Jan-2016, 19-Jan-2016, 23-Jan-2016 Table of Contents Abstract Rationale Repositories to Migrate Migration Plan Requirements for Code-Only Repositories Create a ‘Python core’ team Define commands to move a Mercurial repository to Git CLA enforcement Adding GitHub username support to bugs.python.org A bot to enforce CLA signing Make old repository read-only Requirements for Web-Related Repositories Requirements for the cpython Repository Document steps to commit a pull request Linking pull requests to issues Linking a pull request to an issue Notify the issue if a commit is made Update the linking service for mapping commit IDs to URLs Deprecate sys._mercurial Update the devguide Update PEP 101 Optional, Planned Features Handling Misc/NEWS Handling Misc/ACKS Create https://git.python.org Backup of pull request data Bot to generate cherry-pick pull requests Pull request commit queue A CI service Test coverage report Notifying issues of pull request comments Allow bugs.python.org to use GitHub as a login provider Web hooks for re-generating web content Link web content back to files that it is generated from Splitting out parts of the documentation into their own repositories Backup of Git repositories Identify potential new core developers Status cpython repo Open Issues The fate of hg.python.org Git CLI commands for committing a pull request to cpython Naming the bots Rejected Ideas Separate Python 2 and Python 3 repositories Commit multi-release changes in bugfix branch first Deriving Misc/NEWS from the commit logs Deriving Misc/NEWS from bugs.python.org References Copyright Note CPython’s development process moved to https://github.com/python/cpython on 2017-02-10. Abstract This PEP outlines the steps required to migrate Python’s development process from Mercurial [3] as hosted at hg.python.org [1] to Git [4] on GitHub [2] . Meeting the minimum goals of this PEP should allow for the development process of Python to be as productive as it currently is, and meeting its extended goals should improve the development process from its status quo. Rationale In 2014, it became obvious that Python’s custom development process was becoming a hindrance. As an example, for an external contributor to submit a fix for a bug that eventually was committed, the basic steps were: Open an issue for the bug at bugs.python.org [5] . Checkout out the CPython source code from hg.python.org [1] . Make the fix. Upload a patch. Have a core developer review the patch using our fork of the Rietveld code review tool [6] . Download the patch to make sure it still applies cleanly. Run the test suite manually. Update the NEWS , ACKS , and “What’s New” document as necessary Pull changes to avoid a merge race. Commit the change manually. If the change was for a bugfix release, merge into the in-development branch. Run the test suite manually again. Commit the merge. Push the changes. This is a very heavy, manual process for core developers. Even in the simple case, you could only possibly skip the code review step, as you would still need to build the documentation. This led to patches languishing on the issue tracker due to core developers not being able to work through the backlog fast enough to keep up with submissions. In turn, that led to a side-effect issue of discouraging outside contribution due to frustration from lack of attention, which is a dangerous problem for an open source project with no corporate backing as it runs counter to having a viable future for the project. While allowing patches to be uploaded to bugs.python.org [5] is potentially simple for an external contributor, it is as slow and burdensome as it gets for a core developer to work with. Hence the decision was made in late 2014 that a move to a new development process was needed. A request for PEPs proposing new workflows was made, in the end leading to two: PEP 481 and PEP 507 proposing GitHub [2] and GitLab [7] , respectively. The year 2015 was spent off-and-on working on those proposals and trying to tease out details of what made them different from each other on the core-workflow mailing list [8] . PyCon US 2015 also showed that the community was a bit frustrated with our process due to both cognitive overhead for new contributors and how long it was taking for core developers to look at a patch (see the end of Guido van Rossum’s keynote at PyCon US 2015 [9] as an example of the frustration). On January 1, 2016, the decision was made by Brett Cannon to move the development process to GitHub. The key reasons for choosing GitHub were [10] : Maintaining custom infrastructure has been a burden on volunteers (e.g., an unmaintained, custom fork of Rietveld [6] is currently being used). The custom workflow is very time-consuming for core developers (not enough automated tooling built to help support it). The custom workflow is a hindrance to external contributors (acts as a barrier of entry due to time required to ramp up on development process unique to CPython itself). There is no feature differentiating GitLab from GitHub beyond GitLab being open source. Familiarity with GitHub is far higher among core developers and external contributors than with GitLab. Our BDFL prefers GitHub (who would be the first person to tell you that his opinion shouldn’t matter, but the person making the decision felt it was important that the BDFL feel comfortable with the workflow of his own programming language to encourage his continued participation). There’s even already an unofficial logo to represent the migration to GitHub [22] . The overarching goal of this migration is to improve the development process to the extent that a core developer can go from external contribution submission through all the steps leading to committing said contribution from within a browser on a tablet with WiFi using some development process (this does not inherently mean GitHub’s default workflow). The final solution will also allow an external contributor to contribute even if they chose not to use GitHub (although there is not guarantee in feature parity). Repositories to Migrate While hg.python.org [1] hosts many repositories, there are only five key repositories that need to move: devinabox [12] (done) benchmarks [11] (skipped) peps [13] (done) devguide [14] (done) cpython [15] The devinabox repository is code-only. The peps and devguide repositories involve the generation of webpages. And the cpython repository has special requirements for integration with bugs.python.org [5] . Migration Plan The migration plan is separated into sections based on what is required to migrate the repositories listed in the Repositories to Migrate section. Completion of requirements outlined in each section should unblock the migration of the related repositories. The sections are expected to be completed in order, but not necessarily the requirements within a section. Requirements for Code-Only Repositories Completion of the requirements in this section will allow the devinabox repository to move to GitHub. Create a ‘Python core’ team To manage permissions, a ‘Python core’ team will be created as part of the python organization [16] . Any repository that is moved will have the ‘Python core’ team added to it with write permissions [17] . Anyone who previously had rights to manage SSH keys on hg.python.org will become a team maintainer for the ‘Python core’ team. Define commands to move a Mercurial repository to Git Since moving to GitHub also entails moving to Git [4] , we must decide what tools and commands we will run to translate a Mercurial repository to Git. The tools developed specifically for this migration are hosted at https://github.com/orsenthil/cpython-hg-to-git . CLA enforcement A key part of any open source project is making sure that its source code can be properly licensed. This requires making sure all people making contributions have signed a contributor license agreement (CLA) [18] . Up until now, enforcement of CLA signing of contributed code has been enforced by core developers checking whether someone had an * by their username on bugs.python.org [5] . With this migration, the plan is to start off with automated checking and enforcement of contributors signing the CLA. Adding GitHub username support to bugs.python.org To keep tracking of CLA signing under the direct control of the PSF, tracking who has signed the PSF CLA will be continued by marking that fact as part of someone’s bugs.python.org user profile. What this means is that an association will be needed between a person’s bugs.python.org [5] account and their GitHub account, which will be done through a new field in a user’s profile. This does implicitly require that contributors will need both a GitHub [2] and bugs.python.org account in order to sign the CLA and contribute through GitHub. An API is provided to query bugs.python.org to see if a GitHub username corresponds to someone who has signed the CLA. Making a GET request to e.g. http://bugs.python.org/user?@template=clacheck&github_names=brettcannon,notanuser returns a JSON dictionary with the keys of the usernames requested and a true value if they have signed the CLA, false if they have not, and null if no corresponding GitHub username was found. A bot to enforce CLA signing With an association between someone’s GitHub account and their bugs.python.org [5] account, which has the data as to whether someone has signed the CLA, a bot can monitor pull requests on GitHub and denote whether the contributor has signed the CLA. If the user has signed the CLA, the bot will add a positive label to the issue to denote the pull request has no CLA issues (e.g., a green label stating, “CLA signed”). If the contributor has not signed a CLA, a negative label will be added to the pull request will be blocked using GitHub’s status API (e.g., a red label stating, “CLA not signed”). If a contributor lacks a bugs.python.org account, that will lead to the negative label being used as well. Using a label for both positive and negative cases provides a fallback signal if the bot happens to fail, preventing potential false-positives or false-negatives. It also allows for an easy way to trigger the bot again by simply removing a CLA-related label (this is in contrast to using a GitHub status check [40] which is only triggered on code changes). As no pre-existing bot exists to meet our needs, it will be hosted on Heroku [39] and written to target Python 3.5 to act as a showcase for asynchronous programming. The code for the bot is hosted in the Knights Who Say Ni project [41] . Make old repository read-only Updating .hg/hgrc in the now-old Mercurial repository in the [hooks] section with: pretxnchangegroup . reject = echo " * This repo has been migrated to github.com/python/peps and does not accept new commits in Mercurial!" 2 >& 1 ; exit 1 will make the repository read-only. Requirements for Web-Related Repositories Due to their use for generating webpages, the devguide [14] and peps [13] repositories need their respective processes updated to pull from their new Git repositories. Requirements for the cpython Repository Obviously the most active and important repository currently hosted at hg.python.org [1] is the cpython repository [15] . Because of its importance and high-frequency use, it requires more tooling before being moved to GitHub compared to the other repositories mentioned in this PEP. Document steps to commit a pull request During the process of choosing a new development workflow, it was decided that a linear history is desired. People preferred having a single commit representing a single change instead of having a set of unrelated commits lead to a merge commit that represented a single change. This means that the convenient “Merge” button in GitHub pull requests will be set to only do squash commits and not merge commits. A second set of recommended commands will also be written for committing a contribution from a patch file uploaded to bugs.python.org [5] . This will obviously help keep the linear history, but it will need to be made to have attribution to the patch author. The exact sequence of commands that will be given as guidelines to core developers is an open issue: Git CLI commands for committing a pull request to cpython . Linking pull requests to issues Historically, external contributions were attached to an issue on bugs.python.org [5] thanks to the fact that all external contributions were uploaded as a file. For changes committed by a core developer who committed a change directly, the specifying of an issue number in the commit message of the format Issue # at the start of the message led to a comment being posted to the issue linking to the commit. Linking a pull request to an issue An association between a pull request and an issue is needed to track when a fix has been proposed. The association needs to be many-to-one as there can take multiple pull requests to solve a single issue (technically it should be a many-to-many association for when a single fix solves multiple issues, but this is fairly rare and issues can be merged into one using the Superseder field on the issue tracker). The association between a pull request and an issue will be done based on detecting an issue number. If the issue is specified in either the title or in the body of a message on a pull request then a connection will be made on bugs.python.org [5] . Some visible notification – e.g. label or message – will be made to the pull request to notify that the association was successfully made. Notify the issue if a commit is made Once a commit is made, the corresponding issue should be updated to reflect this fact. This should work regardless of whether the commit came from a pull request or a direct commit. Update the linking service for mapping commit IDs to URLs Currently you can use https://hg.python.org/lookup/ with a revision ID from either the Subversion or Mercurial copies of the cpython repo [15] to get redirected to the URL for that revision in the Mercurial repository. The URL rewriter will need to be updated to redirect to the Git repository and to support the new revision IDs created for the Git repository. The most likely design is to statically know all the Mercurial changeset numbers once the migration has occurred. The lookup code will then be updated to accept hashes from 7 to 40 hexadecimal digits. Any hexadecimal of length 12 or 40 will be compared against the Mercurial changeset numbers. If the number doesn’t match or is of some other length between 7 and 40 then it will be assumed to be a Git hash. The bugs.python.org commit number rewriter will also need to be updated to accept hashes as short as 7 digits as Git will match on hashes that short or longer. Deprecate sys._mercurial Once Python is no longer kept in Mercurial, the sys._mercurial attribute will need to be changed to return ('CPython', '', '') . An equivalent sys._git attribute will be added which fulfills the same use-cases. Update the devguide The devguide will need to be updated with details of the new workflow. Mostly likely work will take place in a separate branch until the migration actually occurs. Update PEP 101 The release process will need to be updated as necessary. Optional, Planned Features Once the cpython repository [15] is migrated, all repositories will have been moved to GitHub [2] and the development process should be on equal footing as before the move. But a key reason for this migration is to improve the development process, making it better than it has ever been. This section outlines some plans on how to improve things. It should be mentioned that overall feature planning for bugs.python.org [5] – which includes plans independent of this migration – are tracked on their own wiki page [23] . Handling Misc/NEWS Traditionally the Misc/NEWS file [19] has been problematic for changes which spanned Python releases. Oftentimes there will be merge conflicts when committing a change between e.g., 3.5 and 3.6 only in the Misc/NEWS file. It’s so common, in fact, that the example instructions in the devguide explicitly mention how to resolve conflicts in the Misc/NEWS file [21] . As part of our tool modernization, working with the Misc/NEWS file will be simplified. The planned approach is to use an individual file per news entry, containing the text for the entry. In this scenario, each feature release would have its own directory for news entries and a separate file would be created in that directory that was either named after the issue it closed or a timestamp value (which prevents collisions). Merges across branches would have no issue as the news entry file would still be uniquely named and in the directory of the latest version that contained the fix. A script would collect all news entry files no matter what directory they reside in and create an appropriate news file (the release directory can be ignored as the mere fact that the file exists is enough to represent that the entry belongs to the release). Classification can either be done by keyword in the new entry file itself or by using subdirectories representing each news entry classification in each release directory (or classification of news entries could be dropped since critical information is captured by the “What’s New” documents which are organized). The benefit of this approach is that it keeps the changes with the code that was actually changed. It also ties the message to being part of the commit which introduced the change. For a commit made through the CLI, a script could be provided to help generate the file. In a bot-driven scenario, the merge bot could have a way to specify a specific news entry and create the file as part of its flattened commit (while most likely also supporting using the first line of the commit message if no specific news entry was specified). If a web-based workflow is used then a status check could be used to verify that a new entry file is in the pull request to act as a reminder that the file is missing. Code for this approach has been written previously for the Mercurial workflow at http://bugs.python.org/issue18967 . There is also tools from the community like https://pypi.python.org/pypi/towncrier , https://github.com/twisted/newsbuilder , and http://docs.openstack.org/developer/reno/ . Discussions at the Sep 2016 Python core-dev sprints led to this decision compared to the rejected approaches outlined in the Rejected Ideas section of this PEP. The separate files approach seems to have the right balance of flexibility and potential tooling out of the various options while solving the motivating problem. Work for this is being tracked at https://github.com/python/core-workflow/issues/6 . Handling Misc/ACKS Traditionally the Misc/ACKS file [20] has been managed by hand. But thanks to Git supporting an author value as well as a committer value per commit, authorship of a commit can be part of the history of the code itself. As such, manual management of Misc/ACKS will become optional. A script will be written that will collect all author and committer names and merge them into Misc/ACKS with all of the names listed prior to the move to Git. Running this script will become part of the release process. The script should also generate a list of all people who contributed since the last execution. This will allow having a list of those who contributed to a specific release so they can be explicitly thanked. Work for this is being tracked at https://github.com/python/core-workflow/issues/7 . Create https://git.python.org Just as hg.python.org [1] currently points to the Mercurial repository for Python, git.python.org should do the equivalent for the Git repository. Backup of pull request data Since GitHub [2] is going to be used for code hosting and code review, those two things need to be backed up. In the case of code hosting, the backup is implicit as all non-shallow Git [4] clones contain the full history of the repository, hence there will be many backups of the repository. The code review history does not have the same implicit backup mechanism as the repository itself. That means a daily backup of code review history should be done so that it is not lost in case of any issues with GitHub. It also helps guarantee that a migration from GitHub to some other code review system is feasible were GitHub to disappear overnight. Bot to generate cherry-pick pull requests Since the decision has been made to work with cherry-picks instead of forward merging of branches, it would be convenient to have a bot that would generate pull requests based on cherry-picking for any pull requests that affect multiple branches. The most likely design is a bot that monitors merged pull requests with key labels applied that delineate what branches the pull request should be cherry-picked into. The bot would then generate cherry-pick pull requests for each label and remove the labels as the pull requests are created (this allows for easy detection when automatic cherry-picking failed). Work for this is being tracked at https://github.com/python/core-workflow/issues/8 . Pull request commit queue This would linearly apply accepted pull requests and verify that the commits did not interfere with each other by running the test suite and backing out commits if the test run failed. To help facilitate the speed of testing, all patches committed since the last test run can be applied at once under a single test run as the optimistic assumption is that the patches will work in tandem. Some mechanism to re-run the tests in case of test flakiness will be needed, whether it is from removing a “test failed” label, web interface for core developers to trigger another testing event, etc. Inspiration or basis of the bot could be taken from pre-existing bots such as Homu [31] or Zuul [32] . The name given to this bot in order to give it commands is an open issue: Naming the bots . A CI service There are various CI services that provide free support for open source projects hosted on GitHub [2] . After experimenting with a couple CI services, the decision was made to go with Travis [33] . The current CI service for Python is Pypatcher [38] . A request can be made in IRC to try a patch from bugs.python.org [5] . The results can be viewed at https://ci.centos.org/job/cPython-build-patch/ . Work for this is being tracked at https://github.com/python/core-workflow/issues/1 . Test coverage report Getting an up-to-date test coverage report for Python’s standard library would be extremely beneficial as generating such a report can take quite a while to produce. There are a couple pre-existing services that provide free test coverage for open source projects. In the end, Codecov [37] was chosen as the best option. Work for this is being tracked at https://github.com/python/core-workflow/issues/2 . Notifying issues of pull request comments The current development process does not include notifying an issue on bugs.python.org [5] when a review comment is left on Rietveld [6] . It would be nice to fix this so that people can subscribe only to comments at bugs.python.org and not GitHub [2] and yet still know when something occurs on GitHub in terms of review comments on relevant pull requests. Current thinking is to post a comment to bugs.python.org to the relevant issue when at least one review comment has been made over a certain period of time (e.g., 15 or 30 minutes, although with GitHub now supporting reviews the time aspect may be unnecessary). This keeps the email volume down for those that receive both GitHub and bugs.python.org email notifications while still making sure that those only following bugs.python.org know when there might be a review comment to address. Allow bugs.python.org to use GitHub as a login provider As of right now, bugs.python.org [5] allows people to log in using Google, Launchpad, or OpenID credentials. It would be good to expand this to GitHub credentials. Web hooks for re-generating web content The content at https://docs.python.org/ , https://docs.python.org/devguide , and https://www.python.org/dev/peps/ are all derived from files kept in one of the repositories to be moved as part of this migration. As such, it would be nice to set up appropriate webhooks to trigger rebuilding the appropriate web content when the files they are based on change instead of having to wait for, e.g., a cronjob to trigger. This can partially be solved if the documentation is a Sphinx project as then the site can have an unofficial mirror on Read the Docs , e.g. http://cpython-devguide.readthedocs.io/ . Work for this is being tracked at https://github.com/python/core-workflow/issues/9 . Link web content back to files that it is generated from It would be helpful for people who find issues with any of the documentation that is generated from a file to have a link on each page which points back to the file on GitHub [2] that stores the content of the page. That would allow for quick pull requests to fix simple things such as spelling mistakes. Work for this is being tracked at http://bugs.python.org/issue28929 . Splitting out parts of the documentation into their own repositories While certain parts of the documentation at https://docs.python.org change with the code, other parts are fairly static and are not tightly bound to the CPython code itself. The following sections of the documentation fit this category of slow-changing, loosely-coupled: Tutorial Python Setup and Usage HOWTOs Installing Python Modules Distributing Python Modules Extending and Embedding FAQs These parts of the documentation could be broken out into their own repositories to simplify their maintenance and to expand who has commit rights to them to ease in their maintenance. It has also been suggested to split out the What’s New documents. That would require deciding whether a workflow could be developed where it would be difficult to forget to update What’s New (potentially through a label added to PRs, like “What’s New needed”). Backup of Git repositories While not necessary, it would be good to have official backups of the various Git repositories for disaster protection. It will be up to the PSF infrastructure committee to decide if this is worthwhile or unnecessary. Identify potential new core developers The Python development team has long-standing guidelines for selecting new core developers. The key part of the guidelines is that a person needs to have contributed multiple patches which have been accepted and are high enough quality and size to demonstrate an understanding of Python’s development process. A bot could be written which tracks patch acceptance rates and generates a report to help identify contributors who warrant consideration for becoming core developers. This work doesn’t even necessarily require GitHub integration as long as the committer field in all git commits is filled in properly. Work is being tracked at https://github.com/python/core-workflow/issues/10 . Status Requirements for migrating the devinabox [12] repository: Completed Adding GitHub username support to bugs.python.org (Maciej Szulik and Ezio Melotti) A bot to enforce CLA signing : https://github.com/python/the-knights-who-say-ni (Brett Cannon) Create a ‘Python core’ team Define commands to move a Mercurial repository to Git : https://github.com/orsenthil/cpython-hg-to-git (Senthil Kumaran) Repositories whose build steps need updating: Completed peps [13] devguide [14] cpython repo [15] Required: Not started Update PEP 101 (commitment from Ned Deily to do this; non-blocker ) In progress Deprecate sys._mercurial ( http://bugs.python.org/issue27593 ; review committal from Ned Deily; non-blocker ) Update the linking service for mapping commit IDs to URLs (code ready, needs deployment once the hg repository is made read-only; https://gist.github.com/brettcannon/f8d97c92b0df264cd4db008ffd32daf9 ; post-migration ) Completed Notify the issue if a commit is made ( http://psf.upfronthosting.co.za/roundup/meta/issue611 ) Track PR status in appropriate issue ( http://psf.upfronthosting.co.za/roundup/meta/issue590 ) Update the devguide , including Document steps to commit a pull request ( https://github.com/python/devguide/milestone/1 ) Update commit hash detection on b.p.o to support 10- and 11-character hashes ( http://psf.upfronthosting.co.za/roundup/meta/issue610 ) Linking a pull request to an issue ( http://psf.upfronthosting.co.za/roundup/meta/issue589 ) Email python-checkins for each commit (PR or direct) ( https://help.github.com/articles/managing-notifications-for-pushes-to-a-repository/ ) Message #python-dev for each commit (PR or direct) ( https://github.com/python/cpython/settings/hooks/new?service=irc ) Get docs built from git ( https://github.com/python/docsbuild-scripts/blob/main/build_docs.py already updated; https://github.com/python/psf-salt/pull/91 to switch) Migrate buildbots to be triggered and pull from GitHub Optional features: Not started Check for whitespace abnormalities as part of CI Create https://git.python.org Backup of pull request data Handling Misc/ACKS Pull request commit queue Allow bugs.python.org to use GitHub as a login provider Web hooks for re-generating web content Splitting out parts of the documentation into their own repositories Backup of Git repositories In progress Notifying issues of pull request comments ( http://psf.upfronthosting.co.za/roundup/meta/issue592 ) Convert b.p.o patches to GitHub PRs ( http://psf.upfronthosting.co.za/roundup/meta/issue600 ) Completed A CI Service Test coverage report Link web content back to files that it is generated from Handling Misc/NEWS Bot to generate cherry-pick pull requests Write .github/CONTRIBUTING.md (to prevent PRs that are inappropriate from even showing up and pointing to the devguide) Open Issues For this PEP, open issues are ones where a decision needs to be made to how to approach or solve a problem. Open issues do not entail coordination issues such as who is going to write a certain bit of code. The fate of hg.python.org With the code repositories moving over to Git [4] , there is no technical need to keep hg.python.org [1] running. Having said that, some in the community would like to have it stay functioning as a Mercurial [3] mirror of the Git repositories. Others have said that they still want a mirror, but one using Git. As maintaining hg.python.org is not necessary, it will be up to the PSF infrastructure committee to decide if they want to spend the time and resources to keep it running. They may also choose whether they want to host a Git mirror on PSF infrastructure. Depending on the decision reached, other ancillary repositories will either be forced to migration or they can choose to simply stay on hg.python.org. Git CLI commands for committing a pull request to cpython Because Git [4] may be a new version control system for core developers, the commands people are expected to run will need to be written down. These commands also need to keep a linear history while giving proper attribution to the pull request author. Another set of commands will also be necessary for when working with a patch file uploaded to bugs.python.org [5] . Here the linear history will be kept implicitly, but it will need to make sure to keep/add attribution. Naming the bots As naming things can lead to bikeshedding of epic proportions, Brett Cannon will choose the final name of the various bots (the name of the project for the bots themselves can be anything, this is purely for the name used in giving commands to the bot or the account name). The names must come from Monty Python, which is only fitting since Python is named after the comedy troupe. Rejected Ideas Separate Python 2 and Python 3 repositories It was discussed whether separate repositories for Python 2 and Python 3 were desired. The thinking was that this would shrink the overall repository size which benefits people with slow Internet connections or small bandwidth caps. In the end it was decided that it was easier logistically to simply keep all of CPython’s history in a single repository. Commit multi-release changes in bugfix branch first As the current development process has changes committed in the oldest branch first and then merged up to the default branch, the question came up as to whether this workflow should be perpetuated. In the end it was decided that committing in the newest branch and then cherry-picking changes into older branches would work best as most people will instinctively work off the newest branch and it is a more common workflow when using Git [4] . Cherry-picking is also more bot-friendly for an in-browser workflow. In the merge-up scenario, if you were to request a bot to do a merge and it failed, then you would have to make sure to immediately solve the merge conflicts if you still allowed the main commit, else you would need to postpone the entire commit until all merges could be handled. With a cherry-picking workflow, the main commit could proceed while postponing the merge-failing cherry-picks. This allows for possibly distributing the work of managing conflicting merges. Lastly, cherry-picking should help avoid merge races. Currently, when one is doing work that spans branches, it takes time to commit in the older branch, possibly push to another clone representing the default branch, merge the change, and then push upstream. Cherry-picking should decouple this so that you don’t have to rush your multi-branch changes as the cherry-pick can be done separately. Deriving Misc/NEWS from the commit logs As part of the discussion surrounding Handling Misc/NEWS , the suggestion has come up of deriving the file from the commit logs itself. In this scenario, the first line of a commit message would be taken to represent the news entry for the change. Some heuristic to tie in whether a change warranted a news entry would be used, e.g., whether an issue number is listed. This idea has been rejected due to some core developers preferring to write a news entry separate from the commit message. The argument is the first line of a commit message compared to that of a news entry have different requirements in terms of brevity, what should be said, etc. Deriving Misc/NEWS from bugs.python.org A rejected solution to the NEWS file problem was to specify the entry on bugs.python.org [5] . This would mean an issue that is marked as “resolved” could not be closed until a news entry is added in the “news” field in the issue tracker. The benefit of tying the news entry to the issue is it makes sure that all changes worthy of a news entry have an accompanying issue. It also makes classifying a news entry automatic thanks to the Component field of the issue. The Versions field of the issue also ties the news entry to which Python releases were affected. A script would be written to query bugs.python.org for relevant new entries for a release and to produce the output needed to be checked into the code repository. This approach is agnostic to whether a commit was done by CLI or bot. A drawback is that there’s a disconnect between the actual commit that made the change and the news entry by having them live in separate places (in this case, GitHub and bugs.python.org). This would mean making a commit would then require remembering to go back to bugs.python.org to add the news entry. References [1] ( 1 , 2 , 3 , 4 , 5 , 6 ) https://hg.python.org [2] ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ) GitHub ( https://github.com ) [3] ( 1 , 2 ) Mercurial ( https://www.mercurial-scm.org/ ) [4] ( 1 , 2 , 3 , 4 , 5 , 6 ) Git ( https://git-scm.com/ ) [5] ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 ) https://bugs.python.org [6] ( 1 , 2 , 3 ) Rietveld ( https://github.com/rietveld-codereview/rietveld ) [ 7 ] GitLab ( https://about.gitlab.com/ ) [ 8 ] core-workflow mailing list ( https://mail.python.org/mailman/listinfo/core-workflow ) [ 9 ] Guido van Rossum’s keynote at PyCon US ( https://www.youtube.com/watch?v=G-uKNd5TSBw ) [ 10 ] Email to core-workflow outlining reasons why GitHub was selected ( https://mail.python.org/pipermail/core-workflow/2016-January/000345.html ) [ 11 ] Mercurial repository for the Unified Benchmark Suite ( https://hg.python.org/benchmarks/ ) [12] ( 1 , 2 ) Mercurial repository for devinabox ( https://hg.python.org/devinabox/ ) [13] ( 1 , 2 , 3 ) Mercurial repository of the Python Enhancement Proposals ( https://hg.python.org/peps/ ) [14] ( 1 , 2 , 3 ) Mercurial repository for the Python Developer’s Guide ( https://hg.python.org/devguide/ ) [15] ( 1 , 2 , 3 , 4 , 5 ) Mercurial repository for CPython ( https://hg.python.org/cpython/ ) [ 16 ] Python organization on GitHub ( https://github.com/python ) [ 17 ] GitHub repository permission levels ( https://help.github.com/enterprise/2.4/user/articles/repository-permission-levels-for-an-organization/ ) [ 18 ] Python Software Foundation Contributor Agreement ( https://www.python.org/psf/contrib/contrib-form/ ) [ 19 ] Misc/NEWS ( https://hg.python.org/cpython/file/default/Misc/NEWS ) [ 20 ] Misc/ACKS ( https://hg.python.org/cpython/file/default/Misc/ACKS ) [ 21 ] Devguide instructions on how to merge across branches ( https://docs.python.org/devguide/committing.html#merging-between-different-branches-within-the-same-major-version ) [ 22 ] Pythocat ( https://octodex.github.com/pythocat ) [ 23 ] Wiki page for bugs.python.org feature development ( https://wiki.python.org/moin/TrackerDevelopmentPlanning ) [24] The “Black Knight” sketch from “Monty Python and the Holy Grail” ( https://www.youtube.com/watch?v=dhRUe-gz690 ) [25] The “Bridge of Death” sketch from “Monty Python and the Holy Grail” ( https://www.youtube.com/watch?v=cV0tCphFMr8 ) [26] “Monty Python and the Holy Grail” sketches ( https://www.youtube.com/playlist?list=PL-Qryc-SVnnu1MvN3r94Y9atpaRuIoGmp ) [27] “Killer rabbit” sketch from “Monty Python and the Holy Grail” ( https://www.youtube.com/watch?v=Nvs5pqf-DMA&list=PL-Qryc-SVnnu1MvN3r94Y9atpaRuIoGmp&index=11 ) [28] “French Taunter” from “Monty Python and the Holy Grail” ( https://www.youtube.com/watch?v=A8yjNbcKkNY&list=PL-Qryc-SVnnu1MvN3r94Y9atpaRuIoGmp&index=13 ) [29] “Constitutional Peasants” from “Monty Python and the Holy Grail” ( https://www.youtube.com/watch?v=JvKIWjnEPNY&list=PL-Qryc-SVnnu1MvN3r94Y9atpaRuIoGmp&index=14 ) [30] “Knights Who Say Ni” from “Monty Python and the Holy Grail” ( https://www.youtube.com/watch?v=zIV4poUZAQo&list=PL-Qryc-SVnnu1MvN3r94Y9atpaRuIoGmp&index=15 ) [ 31 ] Homu ( http://homu.io/ ) [ 32 ] Zuul ( http://docs.openstack.org/infra/zuul/ ) [ 33 ] Travis ( https://travis-ci.org/ ) [34] Codeship ( https://codeship.com/ ) [35] coverage.py ( https://pypi.python.org/pypi/coverage ) [36] Coveralls ( https://coveralls.io/ ) [ 37 ] Codecov ( https://codecov.io/ ) [ 38 ] Pypatcher ( https://github.com/kushaldas/pypatcher ) [ 39 ] Heroku ( https://www.heroku.com/ ) [ 40 ] GitHub status checks ( https://developer.github.com/v3/repos/statuses/ ) [ 41 ] The Knights Who Say Ni project ( https://github.com/python/the-knights-who-say-ni ) Copyright This document has been placed in the public domain. Source: https://github.com/python/peps/blob/main/peps/pep-0512.rst Last modified: 2025-02-01 08:59:27 GMT
#csp.txt
Title: PEP 554 – Multiple Interpreters in the Stdlib | peps.python.org PEP 554 – Multiple Interpreters in the Stdlib Author : Eric Snow <ericsnowcurrently at gmail.com> Discussions-To : Discourse thread Status : Superseded Type : Standards Track Created : 05-Sep-2017 Python-Version : 3.13 Post-History : 07-Sep-2017 , 08-Sep-2017 , 13-Sep-2017 , 05-Dec-2017 , 04-May-2020 , 14-Mar-2023 , 01-Nov-2023 Superseded-By : 734 Table of Contents Abstract Proposal The “interpreters” Module API summary for interpreters module concurrent.futures.InterpreterPoolExecutor Help for Extension Module Maintainers Examples Run isolated code in current OS thread Run in a different thread Pre-populate an interpreter Handling an exception Re-raising an exception Interact with the __main__ namespace Synchronize using an OS pipe Sharing a file descriptor Passing objects via pickle Capturing an interpreter’s stdout Running a module Running as script (including zip archives & directories) Using a channel to communicate Sharing a memoryview (imagine map-reduce) Rationale Concerns About Subinterpreters Concurrency Shared Data Interpreter Isolation Existing Usage Alternate Python Implementations “interpreters” Module API Uncaught Exceptions Interpreter Restrictions API For Communication Shareable Types Communicating Through OS Pipes Channels Caveats For Shared Objects Documentation Alternative Solutions Open Questions Deferred Functionality Add convenience API Avoid possible confusion about interpreters running in the current thread Clarify “running” vs. “has threads” A Dunder Method For Sharing Interpreter.call() Interpreter.run_in_thread() Synchronization Primitives CSP Library Syntactic Support Multiprocessing C-extension opt-in/opt-out Poisoning channels Resetting __main__ Resetting an interpreter’s state Copy an existing interpreter’s state Shareable file descriptors and sockets Integration with async Support for iteration Channel context managers Pipes and Queues Return a lock from send() Support prioritization in channels Support inheriting settings (and more?) Make exceptions shareable Make everything shareable through serialization Make RunFailedError.__cause__ lazy Return a value from interp.exec() Add a shareable synchronization primitive Propagate SystemExit and KeyboardInterrupt Differently Add an explicit release() and close() to channel end classes Add SendChannel.send_buffer() Auto-run in a thread Rejected Ideas Explicit channel association Add an API based on pipes Add an API based on queues “enumerate” Alternate solutions to prevent leaking exceptions across interpreters Always associate each new interpreter with its own thread Only associate interpreters upon use Allow multiple simultaneous calls to Interpreter.exec() Add a “reraise” method to RunFailedError Implementation References Copyright Note This PEP effectively continues in a cleaner form in PEP 734 . This PEP is kept as-is for the sake of the various sections of background information and deferred/rejected ideas that have been stripped from PEP 734 . Abstract CPython has supported multiple interpreters in the same process (AKA “subinterpreters”) since version 1.5 (1997). The feature has been available via the C-API. [c-api] Multiple interpreters operate in relative isolation from one another , which facilitates novel alternative approaches to concurrency . This proposal introduces the stdlib interpreters module. It exposes the basic functionality of multiple interpreters already provided by the C-API, along with basic support for communicating between interpreters. This module is especially relevant since PEP 684 introduced a per-interpreter GIL in Python 3.12. Proposal Summary: add a new stdlib module: “interpreters” add concurrent.futures.InterpreterPoolExecutor help for extension module maintainers The “interpreters” Module The interpreters module will provide a high-level interface to the multiple interpreter functionality, and wrap a new low-level _interpreters (in the same way as the threading module). See the Examples section for concrete usage and use cases. Along with exposing the existing (in CPython) multiple interpreter support, the module will also support a basic mechanism for passing data between interpreters. That involves setting “shareable” objects in the __main__ module of a target subinterpreter. Some such objects, like os.pipe() , may be used to communicate further. The module will also provide a minimal implementation of “channels” as a demonstration of cross-interpreter communication. Note that objects are not shared between interpreters since they are tied to the interpreter in which they were created. Instead, the objects’ data is passed between interpreters. See the Shared Data and API For Communication sections for more details about sharing/communicating between interpreters. API summary for interpreters module Here is a summary of the API for the interpreters module. For a more in-depth explanation of the proposed classes and functions, see the “interpreters” Module API section below. For creating and using interpreters: signature description list_all() -> [Interpreter] Get all existing interpreters. get_current() -> Interpreter Get the currently running interpreter. get_main() -> Interpreter Get the main interpreter. create() -> Interpreter Initialize a new (idle) Python interpreter. signature description class Interpreter A single interpreter. .id The interpreter’s ID (read-only). .is_running() -> bool Is the interpreter currently executing code? .close() Finalize and destroy the interpreter. .set_main_attrs(**kwargs) Bind “shareable” objects in __main__ . .get_main_attr(name) Get a “shareable” object from __main__ . .exec(src_str, /) Run the given source code in the interpreter (in the current thread). For communicating between interpreters: signature description is_shareable(obj) -> Bool Can the object’s data be passed between interpreters? create_channel() -> (RecvChannel, SendChannel) Create a new channel for passing data between interpreters. concurrent.futures.InterpreterPoolExecutor An executor will be added that extends ThreadPoolExecutor to run per-thread tasks in subinterpreters. Initially, the only supported tasks will be whatever Interpreter.exec() takes (e.g. a str script). However, we may also support some functions, as well as eventually a separate method for pickling the task and arguments, to reduce friction (at the expense of performance for short-running tasks). Help for Extension Module Maintainers In practice, an extension that implements multi-phase init ( PEP 489 ) is considered isolated and thus compatible with multiple interpreters. Otherwise it is “incompatible”. Many extension modules are still incompatible. The maintainers and users of such extension modules will both benefit when they are updated to support multiple interpreters. In the meantime, users may become confused by failures when using multiple interpreters, which could negatively impact extension maintainers. See Concerns below. To mitigate that impact and accelerate compatibility, we will do the following: be clear that extension modules are not required to support use in multiple interpreters raise ImportError when an incompatible module is imported in a subinterpreter provide resources (e.g. docs) to help maintainers reach compatibility reach out to the maintainers of Cython and of the most used extension modules (on PyPI) to get feedback and possibly provide assistance Examples Run isolated code in current OS thread interp = interpreters . create () print ( 'before' ) interp . exec ( 'print("during")' ) print ( 'after' ) Run in a different thread interp = interpreters . create () def run (): interp . exec ( 'print("during")' ) t = threading . Thread ( target = run ) print ( 'before' ) t . start () t . join () print ( 'after' ) Pre-populate an interpreter interp = interpreters . create () interp . exec ( tw . dedent ( """ import some_lib import an_expensive_module some_lib.set_up() """ )) wait_for_request () interp . exec ( tw . dedent ( """ some_lib.handle_request() """ )) Handling an exception interp = interpreters . create () try : interp . exec ( tw . dedent ( """ raise KeyError """ )) except interpreters . RunFailedError as exc : print ( f "got the error from the subinterpreter: { exc } " ) Re-raising an exception interp = interpreters . create () try : try : interp . exec ( tw . dedent ( """ raise KeyError """ )) except interpreters . RunFailedError as exc : raise exc . __cause__ except KeyError : print ( "got a KeyError from the subinterpreter" ) Note that this pattern is a candidate for later improvement. Interact with the __main__ namespace interp = interpreters . create () interp . set_main_attrs ( a = 1 , b = 2 ) interp . exec ( tw . dedent ( """ res = do_something(a, b) """ )) res = interp . get_main_attr ( 'res' ) Synchronize using an OS pipe interp = interpreters . create () r1 , s1 = os . pipe () r2 , s2 = os . pipe () def task (): interp . exec ( tw . dedent ( f """ import os os.read( { r1 } , 1) print('during B') os.write( { s2 } , '') """ )) t = threading . thread ( target = task ) t . start () print ( 'before' ) os . write ( s1 , '' ) print ( 'during A' ) os . read ( r2 , 1 ) print ( 'after' ) t . join () Sharing a file descriptor interp = interpreters . create () with open ( 'spamspamspam' ) as infile : interp . set_main_attrs ( fd = infile . fileno ()) interp . exec ( tw . dedent ( f """ import os for line in os.fdopen(fd): print(line) """ )) Passing objects via pickle interp = interpreters . create () r , s = os . pipe () interp . exec ( tw . dedent ( f """ import os import pickle reader = { r } """ )) interp . exec ( tw . dedent ( """ data = b'' c = os.read(reader, 1) while c != b' \x00 ': while c != b' \x00 ': data += c c = os.read(reader, 1) obj = pickle.loads(data) do_something(obj) c = os.read(reader, 1) """ )) for obj in input : data = pickle . dumps ( obj ) os . write ( s , data ) os . write ( s , b ' \x00 ' ) os . write ( s , b ' \x00 ' ) Capturing an interpreter’s stdout interp = interpreters . create () stdout = io . StringIO () with contextlib . redirect_stdout ( stdout ): interp . exec ( tw . dedent ( """ print('spam!') """ )) assert ( stdout . getvalue () == 'spam!' ) # alternately: interp . exec ( tw . dedent ( """ import contextlib, io stdout = io.StringIO() with contextlib.redirect_stdout(stdout): print('spam!') captured = stdout.getvalue() """ )) captured = interp . get_main_attr ( 'captured' ) assert ( captured == 'spam!' ) A pipe ( os.pipe() ) could be used similarly. Running a module interp = interpreters . create () main_module = mod_name interp . exec ( f 'import runpy; runpy.run_module( { main_module !r} )' ) Running as script (including zip archives & directories) interp = interpreters . create () main_script = path_name interp . exec ( f "import runpy; runpy.run_path( { main_script !r} )" ) Using a channel to communicate tasks_recv , tasks = interpreters . create_channel () results , results_send = interpreters . create_channel () def worker (): interp = interpreters . create () interp . set_main_attrs ( tasks = tasks_recv , results = results_send ) interp . exec ( tw . dedent ( """ def handle_request(req): ... def capture_exception(exc): ... while True: try: req = tasks.recv() except Exception: # channel closed break try: res = handle_request(req) except Exception as exc: res = capture_exception(exc) results.send_nowait(res) """ )) threads = [ threading . Thread ( target = worker ) for _ in range ( 20 )] for t in threads : t . start () requests = ... for req in requests : tasks . send ( req ) tasks . close () for t in threads : t . join () Sharing a memoryview (imagine map-reduce) data , chunksize = read_large_data_set () buf = memoryview ( data ) numchunks = ( len ( buf ) + 1 ) / chunksize results = memoryview ( b ' \0 ' * numchunks ) tasks_recv , tasks = interpreters . create_channel () def worker (): interp = interpreters . create () interp . set_main_attrs ( data = buf , results = results , tasks = tasks_recv ) interp . exec ( tw . dedent ( """ while True: try: req = tasks.recv() except Exception: # channel closed break resindex, start, end = req chunk = data[start: end] res = reduce_chunk(chunk) results[resindex] = res """ )) t = threading . Thread ( target = worker ) t . start () for i in range ( numchunks ): if not workers_running (): raise ... start = i * chunksize end = start + chunksize if end > len ( buf ): end = len ( buf ) tasks . send (( start , end , i )) tasks . close () t . join () use_results ( results ) Rationale Running code in multiple interpreters provides a useful level of isolation within the same process. This can be leveraged in a number of ways. Furthermore, subinterpreters provide a well-defined framework in which such isolation may extended. (See PEP 684 .) Alyssa (Nick) Coghlan explained some of the benefits through a comparison with multi-processing [benefits] : [ I ] expect that communicating between subinterpreters is going to end up looking an awful lot like communicating between subprocesses via shared memory . The trade - off between the two models will then be that one still just looks like a single process from the point of view of the outside world , and hence doesn 't place any extra demands on the underlying OS beyond those required to run CPython with a single interpreter , while the other gives much stricter isolation ( including isolating C globals in extension modules ), but also demands much more from the OS when it comes to its IPC capabilities . The security risk profiles of the two approaches will also be quite different , since using subinterpreters won 't require deliberately poking holes in the process isolation that operating systems give you by default . CPython has supported multiple interpreters, with increasing levels of support, since version 1.5. While the feature has the potential to be a powerful tool, it has suffered from neglect because the multiple interpreter capabilities are not readily available directly from Python. Exposing the existing functionality in the stdlib will help reverse the situation. This proposal is focused on enabling the fundamental capability of multiple interpreters, isolated from each other, in the same Python process. This is a new area for Python so there is relative uncertainly about the best tools to provide as companions to interpreters. Thus we minimize the functionality we add in the proposal as much as possible. Concerns “subinterpreters are not worth the trouble” Some have argued that subinterpreters do not add sufficient benefit to justify making them an official part of Python. Adding features to the language (or stdlib) has a cost in increasing the size of the language. So an addition must pay for itself. In this case, multiple interpreter support provide a novel concurrency model focused on isolated threads of execution. Furthermore, they provide an opportunity for changes in CPython that will allow simultaneous use of multiple CPU cores (currently prevented by the GIL–see PEP 684 ). Alternatives to subinterpreters include threading, async, and multiprocessing. Threading is limited by the GIL and async isn’t the right solution for every problem (nor for every person). Multiprocessing is likewise valuable in some but not all situations. Direct IPC (rather than via the multiprocessing module) provides similar benefits but with the same caveat. Notably, subinterpreters are not intended as a replacement for any of the above. Certainly they overlap in some areas, but the benefits of subinterpreters include isolation and (potentially) performance. In particular, subinterpreters provide a direct route to an alternate concurrency model (e.g. CSP) which has found success elsewhere and will appeal to some Python users. That is the core value that the interpreters module will provide. “stdlib support for multiple interpreters adds extra burden on C extension authors” In the Interpreter Isolation section below we identify ways in which isolation in CPython’s subinterpreters is incomplete. Most notable is extension modules that use C globals to store internal state. ( PEP 3121 and PEP 489 provide a solution to that problem, followed by some extra APIs that improve efficiency, e.g. PEP 573 ). Consequently, projects that publish extension modules may face an increased maintenance burden as their users start using subinterpreters, where their modules may break. This situation is limited to modules that use C globals (or use libraries that use C globals) to store internal state. For numpy, the reported-bug rate is one every 6 months. [bug-rate] Ultimately this comes down to a question of how often it will be a problem in practice: how many projects would be affected, how often their users will be affected, what the additional maintenance burden will be for projects, and what the overall benefit of subinterpreters is to offset those costs. The position of this PEP is that the actual extra maintenance burden will be small and well below the threshold at which subinterpreters are worth it. “creating a new concurrency API deserves much more thought and experimentation, so the new module shouldn’t go into the stdlib right away, if ever” Introducing an API for a new concurrency model, like happened with asyncio, is an extremely large project that requires a lot of careful consideration. It is not something that can be done as simply as this PEP proposes and likely deserves significant time on PyPI to mature. (See Nathaniel’s post on python-dev.) However, this PEP does not propose any new concurrency API. At most it exposes minimal tools (e.g. subinterpreters, channels) which may be used to write code that follows patterns associated with (relatively) new-to-Python concurrency models . Those tools could also be used as the basis for APIs for such concurrency models. Again, this PEP does not propose any such API. “there is no point to exposing subinterpreters if they still share the GIL” “the effort to make the GIL per-interpreter is disruptive and risky” A common misconception is that this PEP also includes a promise that interpreters will no longer share the GIL. When that is clarified, the next question is “what is the point?”. This is already answered at length in this PEP. Just to be clear, the value lies in: * increase exposure of the existing feature , which helps improve the code health of the entire CPython runtime * expose the ( mostly ) isolated execution of interpreters * preparation for per - interpreter GIL * encourage experimentation “data sharing can have a negative impact on cache performance in multi-core scenarios” (See [cache-line-ping-pong] .) This shouldn’t be a problem for now as we have no immediate plans to actually share data between interpreters, instead focusing on copying. About Subinterpreters Concurrency Concurrency is a challenging area of software development. Decades of research and practice have led to a wide variety of concurrency models, each with different goals. Most center on correctness and usability. One class of concurrency models focuses on isolated threads of execution that interoperate through some message passing scheme. A notable example is Communicating Sequential Processes [CSP] (upon which Go’s concurrency is roughly based). The intended isolation inherent to CPython’s interpreters makes them well-suited to this approach. Shared Data CPython’s interpreters are inherently isolated (with caveats explained below), in contrast to threads. So the same communicate-via-shared-memory approach doesn’t work. Without an alternative, effective use of concurrency via multiple interpreters is significantly limited. The key challenge here is that sharing objects between interpreters faces complexity due to various constraints on object ownership, visibility, and mutability. At a conceptual level it’s easier to reason about concurrency when objects only exist in one interpreter at a time. At a technical level, CPython’s current memory model limits how Python objects may be shared safely between interpreters; effectively, objects are bound to the interpreter in which they were created. Furthermore, the complexity of object sharing increases as interpreters become more isolated, e.g. after GIL removal (though this is mitigated somewhat for some “immortal” objects (see PEP 683 ). Consequently, the mechanism for sharing needs to be carefully considered. There are a number of valid solutions, several of which may be appropriate to support in Python’s stdlib and C-API. Any such solution is likely to share many characteristics with the others. In the meantime, we propose here a minimal solution ( Interpreter.set_main_attrs() ), which sets some precedent for how objects are shared. More importantly, it facilitates the introduction of more advanced approaches later and allows them to coexist and cooperate. In part to demonstrate that, we will provide a basic implementation of “channels”, as a somewhat more advanced sharing solution. Separate proposals may cover: the addition of a public C-API based on the implementation Interpreter.set_main_attrs() the addition of other sharing approaches to the “interpreters” module The fundamental enabling feature for communication is that most objects can be converted to some encoding of underlying raw data, which is safe to be passed between interpreters. For example, an int object can be turned into a C long value, sent to another interpreter, and turned back into an int object there. As another example, None may be passed as-is. Regardless, the effort to determine the best way forward here is mostly outside the scope of this PEP. In the meantime, this proposal describes a basic interim solution using pipes ( os.pipe() ), as well as providing a dedicated capability (“channels”). See API For Communication below. Interpreter Isolation CPython’s interpreters are intended to be strictly isolated from each other. Each interpreter has its own copy of all modules, classes, functions, and variables. The same applies to state in C, including in extension modules. The CPython C-API docs explain more. [caveats] However, there are ways in which interpreters do share some state. First of all, some process-global state remains shared: file descriptors low-level env vars process memory (though allocators are isolated) builtin types (e.g. dict, bytes) singletons (e.g. None) underlying static module data (e.g. functions) for builtin/extension/frozen modules There are no plans to change this. Second, some isolation is faulty due to bugs or implementations that did not take subinterpreters into account. This includes things like extension modules that rely on C globals. [cryptography] In these cases bugs should be opened (some are already): readline module hook functions ( http://bugs.python.org/issue4202 ) memory leaks on re-init ( http://bugs.python.org/issue21387 ) Finally, some potential isolation is missing due to the current design of CPython. Improvements are currently going on to address gaps in this area: extensions using the PyGILState_* API are somewhat incompatible [gilstate] Existing Usage Multiple interpreter support has not been a widely used feature. In fact, there have been only a handful of documented cases of widespread usage, including mod_wsgi , OpenStack Ceph , and JEP . On the one hand, these cases provide confidence that existing multiple interpreter support is relatively stable. On the other hand, there isn’t much of a sample size from which to judge the utility of the feature. Alternate Python Implementations I’ve solicited feedback from various Python implementors about support for subinterpreters. Each has indicated that they would be able to support multiple interpreters in the same process (if they choose to) without a lot of trouble. Here are the projects I contacted: jython ( [jython] ) ironpython (personal correspondence) pypy (personal correspondence) micropython (personal correspondence) “interpreters” Module API The module provides the following functions: list_all () -> [ Interpreter ] Return a list of all existing interpreters . get_current () => Interpreter Return the currently running interpreter . get_main () => Interpreter Return the main interpreter . If the Python implementation has no concept of a main interpreter then return None . create () -> Interpreter Initialize a new Python interpreter and return it . It will remain idle until something is run in it and always run in its own thread . is_shareable ( obj ) -> bool : Return True if the object may be "shared" between interpreters . This does not necessarily mean that the actual objects will be shared . Instead , it means that the objects ' underlying data will be shared in a cross - interpreter way , whether via a proxy , a copy , or some other means . The module also provides the following class: class Interpreter(id): id -> int: The interpreter's ID. (read-only) is_running() -> bool: Return whether or not the interpreter's "exec()" is currently executing code. Code running in subthreads is ignored. Calling this on the current interpreter will always return True. close(): Finalize and destroy the interpreter. This may not be called on an already running interpreter. Doing so results in a RuntimeError. set_main_attrs(iterable_or_mapping, /): set_main_attrs(**kwargs): Set attributes in the interpreter's __main__ module corresponding to the given name-value pairs. Each value must be a "shareable" object and will be converted to a new object (e.g. copy, proxy) in whatever way that object's type defines. If an attribute with the same name is already set, it will be overwritten. This method is helpful for setting up an interpreter before calling exec(). get_main_attr(name, default=None, /): Return the value of the corresponding attribute of the interpreter's __main__ module. If the attribute isn't set then the default is returned. If it is set, but the value isn't "shareable" then a ValueError is raised. This may be used to introspect the __main__ module, as well as a very basic mechanism for "returning" one or more results from Interpreter.exec(). exec(source_str, /): Run the provided Python source code in the interpreter, in its __main__ module. This may not be called on an already running interpreter. Doing so results in a RuntimeError. An "interp.exec()" call is similar to a builtin exec() call (or to calling a function that returns None). Once "interp.exec()" completes, the code that called "exec()" continues executing (in the original interpreter). Likewise, if there is any uncaught exception then it effectively (see below) propagates into the code where ``interp.exec()`` was called. Like exec() (and threads), but unlike function calls, there is no return value. If any "return" value from the code is needed, send the data out via a pipe (os.pipe()) or channel or other cross-interpreter communication mechanism. The big difference from exec() or functions is that "interp.exec()" executes the code in an entirely different interpreter, with entirely separate state. The interpreters are completely isolated from each other, so the state of the original interpreter (including the code it was executing in the current OS thread) does not affect the state of the target interpreter (the one that will execute the code). Likewise, the target does not affect the original, nor any of its other threads. Instead, the state of the original interpreter (for this thread) is frozen, and the code it's executing code completely blocks. At that point, the target interpreter is given control of the OS thread. Then, when it finishes executing, the original interpreter gets control back and continues executing. So calling "interp.exec()" will effectively cause the current Python thread to completely pause. Sometimes you won't want that pause, in which case you should make the "exec()" call in another thread. To do so, add a function that calls "interp.exec()" and then run that function in a normal "threading.Thread". Note that the interpreter's state is never reset, neither before "interp.exec()" executes the code nor after. Thus the interpreter state is preserved between calls to "interp.exec()". This includes "sys.modules", the "builtins" module, and the internal state of C extension modules. Also note that "interp.exec()" executes in the namespace of the "__main__" module, just like scripts, the REPL, "-m", and "-c". Just as the interpreter's state is not ever reset, the "__main__" module is never reset. You can imagine concatenating the code from each "interp.exec()" call into one long script. This is the same as how the REPL operates. Supported code: source text. In addition to the functionality of Interpreter.set_main_attrs() , the module provides a related way to pass data between interpreters: channels. See Channels below. Uncaught Exceptions Regarding uncaught exceptions in Interpreter.exec() , we noted that they are “effectively” propagated into the code where interp.exec() was called. To prevent leaking exceptions (and tracebacks) between interpreters, we create a surrogate of the exception and its traceback (see traceback.TracebackException ), set it to __cause__ on a new interpreters.RunFailedError , and raise that. Directly raising (a proxy of) the exception is problematic since it’s harder to distinguish between an error in the interp.exec() call and an uncaught exception from the subinterpreter. Interpreter Restrictions Every new interpreter created by interpreters.create() now has specific restrictions on any code it runs. This includes the following: importing an extension module fails if it does not implement multi-phase init daemon threads may not be created os.fork() is not allowed (so no multiprocessing ) os.exec*() is not allowed (but “fork+exec”, a la subprocess is okay) Note that interpreters created with the existing C-API do not have these restrictions. The same is true for the “main” interpreter, so existing use of Python will not change. We may choose to later loosen some of the above restrictions or provide a way to enable/disable granular restrictions individually. Regardless, requiring multi-phase init from extension modules will always be a default restriction. API For Communication As discussed in Shared Data above, multiple interpreter support is less useful without a mechanism for sharing data (communicating) between them. Sharing actual Python objects between interpreters, however, has enough potential problems that we are avoiding support for that in this proposal. Nor, as mentioned earlier, are we adding anything more than a basic mechanism for communication. That mechanism is the Interpreter.set_main_attrs() method. It may be used to set up global variables before Interpreter.exec() is called. The name-value pairs passed to set_main_attrs() are bound as attributes of the interpreter’s __main__ module. The values must be “shareable”. See Shareable Types below. Additional approaches to communicating and sharing objects are enabled through Interpreter.set_main_attrs() . A shareable object could be implemented which works like a queue, but with cross-interpreter safety. In fact, this PEP does include an example of such an approach: channels. Shareable Types An object is “shareable” if its type supports shareable instances. The type must implement a new internal protocol, which is used to convert an object to interpreter-independent data and then converted back to an object on the other side. Also see is_shareable() above. A minimal set of simple, immutable builtin types will be supported initially, including: None bool bytes str int float We will also support a small number of complex types initially: memoryview , to allow sharing PEP 3118 buffers channels Further builtin types may be supported later, complex or not. Limiting the initial shareable types is a practical matter, reducing the potential complexity of the initial implementation. There are a number of strategies we may pursue in the future to expand supported objects, once we have more experience with interpreter isolation. In the meantime, a separate proposal will discuss making the internal protocol (and C-API) used by Interpreter.set_main_attrs() public. With that protocol, support for other types could be added by extension modules. Communicating Through OS Pipes Even without a dedicated object for communication, users may already use existing tools. For example, one basic approach for sending data between interpreters is to use a pipe (see os.pipe() ): interpreter A calls os.pipe() to get a read/write pair of file descriptors (both int objects) interpreter A calls interp.set_main_attrs() , binding the read FD (or embeds it using string formatting) interpreter A calls interp.exec() on interpreter B interpreter A writes some bytes to the write FD interpreter B reads those bytes Several of the earlier examples demonstrate this, such as Synchronize using an OS pipe . Channels The interpreters module will include a dedicated solution for passing object data between interpreters: channels. They are included in the module in part to provide an easier mechanism than using os.pipe() and in part to demonstrate how libraries may take advantage of Interpreter.set_main_attrs() and the protocol it uses. A channel is a simplex FIFO. It is a basic, opt-in data sharing mechanism that draws inspiration from pipes, queues, and CSP’s channels. [fifo] The main difference from pipes is that channels can be associated with zero or more interpreters on either end. Like queues, which are also many-to-many, channels are buffered (though they also offer methods with unbuffered semantics). Channels have two operations: send and receive. A key characteristic of those operations is that channels transmit data derived from Python objects rather than the objects themselves. When objects are sent, their data is extracted. When the “object” is received in the other interpreter, the data is converted back into an object owned by that interpreter. To make this work, the mutable shared state will be managed by the Python runtime, not by any of the interpreters. Initially we will support only one type of objects for shared state: the channels provided by interpreters.create_channel() . Channels, in turn, will carefully manage passing objects between interpreters. This approach, including keeping the API minimal, helps us avoid further exposing any underlying complexity to Python users. The interpreters module provides the following function related to channels: create_channel () -> ( RecvChannel , SendChannel ): Create a new channel and return ( recv , send ), the RecvChannel and SendChannel corresponding to the ends of the channel . Both ends of the channel are supported "shared" objects ( i . e . may be safely shared by different interpreters . Thus they may be set using "Interpreter.set_main_attrs()" . The module also provides the following channel-related classes: class RecvChannel ( id ): The receiving end of a channel . An interpreter may use this to receive objects from another interpreter . Any type supported by Interpreter . set_main_attrs () will be supported here , though at first only a few of the simple , immutable builtin types will be supported . id -> int : The channel 's unique ID. The "send" end has the same one. recv ( * , timeout = None ): Return the next object from the channel . If none have been sent then wait until the next send ( or until the timeout is hit ) . At the least , the object will be equivalent to the sent object . That will almost always mean the same type with the same data , though it could also be a compatible proxy . Regardless , it may use a copy of that data or actually share the data . That 's up to the object 's type. recv_nowait ( default = None ): Return the next object from the channel . If none have been sent then return the default . Otherwise , this is the same as the "recv()" method . class SendChannel ( id ): The sending end of a channel . An interpreter may use this to send objects to another interpreter . Any type supported by Interpreter . set_main_attrs () will be supported here , though at first only a few of the simple , immutable builtin types will be supported . id -> int : The channel 's unique ID. The "recv" end has the same one. send ( obj , * , timeout = None ): Send the object ( i . e . its data ) to the "recv" end of the channel . Wait until the object is received . If the object is not shareable then ValueError is raised . The builtin memoryview is supported , so sending a buffer across involves first wrapping the object in a memoryview and then sending that . send_nowait ( obj ): Send the object to the "recv" end of the channel . This behaves the same as "send()" , except for the waiting part . If no interpreter is currently receiving ( waiting on the other end ) then queue the object and return False . Otherwise return True . Caveats For Shared Objects Again, Python objects are not shared between interpreters. However, in some cases data those objects wrap is actually shared and not just copied. One example might be PEP 3118 buffers. In those cases the object in the original interpreter is kept alive until the shared data in the other interpreter is no longer used. Then object destruction can happen like normal in the original interpreter, along with the previously shared data. Documentation The new stdlib docs page for the interpreters module will include the following: (at the top) a clear note that support for multiple interpreters is not required from extension modules some explanation about what subinterpreters are brief examples of how to use multiple interpreters (and communicating between them) a summary of the limitations of using multiple interpreters (for extension maintainers) a link to the resources for ensuring multiple interpreters compatibility much of the API information in this PEP Docs about resources for extension maintainers already exist on the Isolating Extension Modules howto page. Any extra help will be added there. For example, it may prove helpful to discuss strategies for dealing with linked libraries that keep their own subinterpreter-incompatible global state. Note that the documentation will play a large part in mitigating any negative impact that the new interpreters module might have on extension module maintainers. Also, the ImportError for incompatible extension modules will be updated to clearly say it is due to missing multiple interpreters compatibility and that extensions are not required to provide it. This will help set user expectations properly. Alternative Solutions One possible alternative to a new module is to add support for interpreters to concurrent.futures . There are several reasons why that wouldn’t work: the obvious place to look for multiple interpreters support is an “interpreters” module, much as with “threading”, etc. concurrent.futures is all about executing functions but currently we don’t have a good way to run a function from one interpreter in another Similar reasoning applies for support in the multiprocessing module. Open Questions will is be too confusing that interp.exec() runs in the current thread? should we add pickling fallbacks right now for interp.exec() , and/or Interpreter.set_main_attrs() and Interpreter.get_main_attr() ? should we support (limited) functions in interp.exec() right now? rename Interpreter.close() to Interpreter.destroy() ? drop Interpreter.get_main_attr() , since we have channels? should channels be its own PEP? Deferred Functionality In the interest of keeping this proposal minimal, the following functionality has been left out for future consideration. Note that this is not a judgement against any of said capability, but rather a deferment. That said, each is arguably valid. Add convenience API There are a number of things I can imagine would smooth out hypothetical rough edges with the new module: add something like Interpreter.run() or Interpreter.call() that calls interp.exec() and falls back to pickle fall back to pickle in Interpreter.set_main_attrs() and Interpreter.get_main_attr() These would be easy to do if this proves to be a pain point. Avoid possible confusion about interpreters running in the current thread One regular point of confusion has been that Interpreter.exec() executes in the current OS thread, temporarily blocking the current Python thread. It may be worth doing something to avoid that confusion. Some possible solutions for this hypothetical problem: by default, run in a new thread? add Interpreter.exec_in_thread() ? add Interpreter.exec_in_current_thread() ? In earlier versions of this PEP the method was interp.run() . The simple change to interp.exec() alone will probably reduce confusion sufficiently, when coupled with educating users via the docs. It it turns out to be a real problem, we can pursue one of the alternatives at that point. Clarify “running” vs. “has threads” Interpreter.is_running() refers specifically to whether or not Interpreter.exec() (or similar) is running somewhere. It does not say anything about if the interpreter has any subthreads running. That information might be helpful. Some things we could do: rename Interpreter.is_running() to Interpreter.is_running_main() add Interpreter.has_threads() , to complement Interpreter.is_running() expand to Interpreter.is_running(main=True, threads=False) None of these are urgent and any could be done later, if desired. A Dunder Method For Sharing We could add a special method, like __xid__ to correspond to tp_xid . At the very least, it would allow Python types to convert their instances to some other type that implements tp_xid . The problem is that exposing this capability to Python code presents a degree of complixity that hasn’t been explored yet, nor is there a compelling case to investigate that complexity. Interpreter.call() It would be convenient to run existing functions in subinterpreters directly. Interpreter.exec() could be adjusted to support this or a call() method could be added: Interpreter . call ( f , * args , ** kwargs ) This suffers from the same problem as sharing objects between interpreters via queues. The minimal solution (running a source string) is sufficient for us to get the feature out where it can be explored. Interpreter.run_in_thread() This method would make a interp.exec() call for you in a thread. Doing this using only threading.Thread and interp.exec() is relatively trivial so we’ve left it out. Synchronization Primitives The threading module provides a number of synchronization primitives for coordinating concurrent operations. This is especially necessary due to the shared-state nature of threading. In contrast, interpreters do not share state. Data sharing is restricted to the runtime’s shareable objects capability, which does away with the need for explicit synchronization. If any sort of opt-in shared state support is added to CPython’s interpreters in the future, that same effort can introduce synchronization primitives to meet that need. CSP Library A csp module would not be a large step away from the functionality provided by this PEP. However, adding such a module is outside the minimalist goals of this proposal. Syntactic Support The Go language provides a concurrency model based on CSP, so it’s similar to the concurrency model that multiple interpreters support. However, Go also provides syntactic support, as well as several builtin concurrency primitives, to make concurrency a first-class feature. Conceivably, similar syntactic (and builtin) support could be added to Python using interpreters. However, that is way outside the scope of this PEP! Multiprocessing The multiprocessing module could support interpreters in the same way it supports threads and processes. In fact, the module’s maintainer, Davin Potts, has indicated this is a reasonable feature request. However, it is outside the narrow scope of this PEP. C-extension opt-in/opt-out By using the PyModuleDef_Slot introduced by PEP 489 , we could easily add a mechanism by which C-extension modules could opt out of multiple interpreter support. Then the import machinery, when operating in a subinterpreter, would need to check the module for support. It would raise an ImportError if unsupported. Alternately we could support opting in to multiple interpreters support. However, that would probably exclude many more modules (unnecessarily) than the opt-out approach. Also, note that PEP 489 defined that an extension’s use of the PEP’s machinery implies multiple interpreters support. The scope of adding the ModuleDef slot and fixing up the import machinery is non-trivial, but could be worth it. It all depends on how many extension modules break under subinterpreters. Given that there are relatively few cases we know of through mod_wsgi, we can leave this for later. Poisoning channels CSP has the concept of poisoning a channel. Once a channel has been poisoned, any send() or recv() call on it would raise a special exception, effectively ending execution in the interpreter that tried to use the poisoned channel. This could be accomplished by adding a poison() method to both ends of the channel. The close() method can be used in this way (mostly), but these semantics are relatively specialized and can wait. Resetting __main__ As proposed, every call to Interpreter.exec() will execute in the namespace of the interpreter’s existing __main__ module. This means that data persists there between interp.exec() calls. Sometimes this isn’t desirable and you want to execute in a fresh __main__ . Also, you don’t necessarily want to leak objects there that you aren’t using any more. Note that the following won’t work right because it will clear too much (e.g. __name__ and the other “__dunder__” attributes: interp . exec ( 'globals().clear()' ) Possible solutions include: a create() arg to indicate resetting __main__ after each interp.exec() call an Interpreter.reset_main flag to support opting in or out after the fact an Interpreter.reset_main() method to opt in when desired importlib.util.reset_globals() [reset_globals] Also note that resetting __main__ does nothing about state stored in other modules. So any solution would have to be clear about the scope of what is being reset. Conceivably we could invent a mechanism by which any (or every) module could be reset, unlike reload() which does not clear the module before loading into it. Regardless, since __main__ is the execution namespace of the interpreter, resetting it has a much more direct correlation to interpreters and their dynamic state than does resetting other modules. So a more generic module reset mechanism may prove unnecessary. This isn’t a critical feature initially. It can wait until later if desirable. Resetting an interpreter’s state It may be nice to re-use an existing subinterpreter instead of spinning up a new one. Since an interpreter has substantially more state than just the __main__ module, it isn’t so easy to put an interpreter back into a pristine/fresh state. In fact, there may be parts of the state that cannot be reset from Python code. A possible solution is to add an Interpreter.reset() method. This would put the interpreter back into the state it was in when newly created. If called on a running interpreter it would fail (hence the main interpreter could never be reset). This would likely be more efficient than creating a new interpreter, though that depends on what optimizations will be made later to interpreter creation. While this would potentially provide functionality that is not otherwise available from Python code, it isn’t a fundamental functionality. So in the spirit of minimalism here, this can wait. Regardless, I doubt it would be controversial to add it post-PEP. Copy an existing interpreter’s state Relatedly, it may be useful to support creating a new interpreter based on an existing one, e.g. Interpreter.copy() . This ties into the idea that a snapshot could be made of an interpreter’s memory, which would make starting up CPython, or creating new interpreters, faster in general. The same mechanism could be used for a hypothetical Interpreter.reset() , as described previously. Shareable file descriptors and sockets Given that file descriptors and sockets are process-global resources, making them shareable is a reasonable idea. They would be a good candidate for the first effort at expanding the supported shareable types. They aren’t strictly necessary for the initial API. Integration with async Per Antoine Pitrou [async] : Has any thought been given to how FIFOs could integrate with async code driven by an event loop (e.g. asyncio)? I think the model of executing several asyncio (or Tornado) applications each in their own subinterpreter may prove quite interesting to reconcile multi- core concurrency with ease of programming. That would require the FIFOs to be able to synchronize on something an event loop can wait on (probably a file descriptor?). The basic functionality of multiple interpreters support does not depend on async and can be added later. A possible solution is to provide async implementations of the blocking channel methods ( recv() , and send() ). Alternately, “readiness callbacks” could be used to simplify use in async scenarios. This would mean adding an optional callback (kw-only) parameter to the recv_nowait() and send_nowait() channel methods. The callback would be called once the object was sent or received (respectively). (Note that making channels buffered makes readiness callbacks less important.) Support for iteration Supporting iteration on RecvChannel (via __iter__() or _next__() ) may be useful. A trivial implementation would use the recv() method, similar to how files do iteration. Since this isn’t a fundamental capability and has a simple analog, adding iteration support can wait until later. Channel context managers Context manager support on RecvChannel and SendChannel may be helpful. The implementation would be simple, wrapping a call to close() (or maybe release() ) like files do. As with iteration, this can wait. Pipes and Queues With the proposed object passing mechanism of “os.pipe()”, other similar basic types aren’t strictly required to achieve the minimal useful functionality of multiple interpreters. Such types include pipes (like unbuffered channels, but one-to-one) and queues (like channels, but more generic). See below in Rejected Ideas for more information. Even though these types aren’t part of this proposal, they may still be useful in the context of concurrency. Adding them later is entirely reasonable. The could be trivially implemented as wrappers around channels. Alternatively they could be implemented for efficiency at the same low level as channels. Return a lock from send() When sending an object through a channel, you don’t have a way of knowing when the object gets received on the other end. One way to work around this is to return a locked threading.Lock from SendChannel.send() that unlocks once the object is received. Alternately, the proposed SendChannel.send() (blocking) and SendChannel.send_nowait() provide an explicit distinction that is less likely to confuse users. Note that returning a lock would matter for buffered channels (i.e. queues). For unbuffered channels it is a non-issue. Support prioritization in channels A simple example is queue.PriorityQueue in the stdlib. Support inheriting settings (and more?) Folks might find it useful, when creating a new interpreter, to be able to indicate that they would like some things “inherited” by the new interpreter. The mechanism could be a strict copy or it could be copy-on-write. The motivating example is with the warnings module (e.g. copy the filters). The feature isn’t critical, nor would it be widely useful, so it can wait until there’s interest. Notably, both suggested solutions will require significant work, especially when it comes to complex objects and most especially for mutable containers of mutable complex objects. Make exceptions shareable Exceptions are propagated out of run() calls, so it isn’t a big leap to make them shareable. However, as noted elsewhere, it isn’t essential or (particularly common) so we can wait on doing that. Make everything shareable through serialization We could use pickle (or marshal) to serialize everything and thus make them shareable. Doing this is potentially inefficient, but it may be a matter of convenience in the end. We can add it later, but trying to remove it later would be significantly more painful. Make RunFailedError.__cause__ lazy An uncaught exception in a subinterpreter (from interp.exec() ) is copied to the calling interpreter and set as __cause__ on a RunFailedError which is then raised. That copying part involves some sort of deserialization in the calling interpreter, which can be expensive (e.g. due to imports) yet is not always necessary. So it may be useful to use an ExceptionProxy type to wrap the serialized exception and only deserialize it when needed. That could be via ExceptionProxy__getattribute__() or perhaps through RunFailedError.resolve() (which would raise the deserialized exception and set RunFailedError.__cause__ to the exception. It may also make sense to have RunFailedError.__cause__ be a descriptor that does the lazy deserialization (and set __cause__ ) on the RunFailedError instance. Return a value from interp.exec() Currently interp.exec() always returns None. One idea is to return the return value from whatever the subinterpreter ran. However, for now it doesn’t make sense. The only thing folks can run is a string of code (i.e. a script). This is equivalent to PyRun_StringFlags() , exec() , or a module body. None of those “return” anything. We can revisit this once interp.exec() supports functions, etc. Add a shareable synchronization primitive This would be _threading.Lock (or something like it) where interpreters would actually share the underlying mutex. The main concern is that locks and isolated interpreters may not mix well (as learned in Go). We can add this later if it proves desirable without much trouble. Propagate SystemExit and KeyboardInterrupt Differently The exception types that inherit from BaseException (aside from Exception ) are usually treated specially. These types are: KeyboardInterrupt , SystemExit , and GeneratorExit . It may make sense to treat them specially when it comes to propagation from interp.exec() . Here are some options: * propagate like normal via RunFailedError * do not propagate ( handle them somehow in the subinterpreter ) * propagate them directly ( avoid RunFailedError ) * propagate them directly ( set RunFailedError as __cause__ ) We aren’t going to worry about handling them differently. Threads already ignore SystemExit , so for now we will follow that pattern. Add an explicit release() and close() to channel end classes It can be convenient to have an explicit way to close a channel against further global use. Likewise it could be useful to have an explicit way to release one of the channel ends relative to the current interpreter. Among other reasons, such a mechanism is useful for communicating overall state between interpreters without the extra boilerplate that passing objects through a channel directly would require. The challenge is getting automatic release/close right without making it hard to understand. This is especially true when dealing with a non-empty channel. We should be able to get by without release/close for now. Add SendChannel.send_buffer() This method would allow no-copy sending of an object through a channel if it supports the PEP 3118 buffer protocol (e.g. memoryview). Support for this is not fundamental to channels and can be added on later without much disruption. Auto-run in a thread The PEP proposes a hard separation between subinterpreters and threads: if you want to run in a thread you must create the thread yourself and call interp.exec() in it. However, it might be convenient if interp.exec() could do that for you, meaning there would be less boilerplate. Furthermore, we anticipate that users will want to run in a thread much more often than not. So it would make sense to make this the default behavior. We would add a kw-only param “threaded” (default True ) to interp.exec() to allow the run-in-the-current-thread operation. Rejected Ideas Explicit channel association Interpreters are implicitly associated with channels upon recv() and send() calls. They are de-associated with release() calls. The alternative would be explicit methods. It would be either add_channel() and remove_channel() methods on Interpreter objects or something similar on channel objects. In practice, this level of management shouldn’t be necessary for users. So adding more explicit support would only add clutter to the API. Add an API based on pipes A pipe would be a simplex FIFO between exactly two interpreters. For most use cases this would be sufficient. It could potentially simplify the implementation as well. However, it isn’t a big step to supporting a many-to-many simplex FIFO via channels. Also, with pipes the API ends up being slightly more complicated, requiring naming the pipes. Add an API based on queues Queues and buffered channels are almost the same thing. The main difference is that channels have a stronger relationship with context (i.e. the associated interpreter). The name “Channel” was used instead of “Queue” to avoid confusion with the stdlib queue.Queue . “enumerate” The list_all() function provides the list of all interpreters. In the threading module, which partly inspired the proposed API, the function is called enumerate() . The name is different here to avoid confusing Python users that are not already familiar with the threading API. For them “enumerate” is rather unclear, whereas “list_all” is clear. Alternate solutions to prevent leaking exceptions across interpreters In function calls, uncaught exceptions propagate to the calling frame. The same approach could be taken with interp.exec() . However, this would mean that exception objects would leak across the inter-interpreter boundary. Likewise, the frames in the traceback would potentially leak. While that might not be a problem currently, it would be a problem once interpreters get better isolation relative to memory management (which is necessary to stop sharing the GIL between interpreters). We’ve resolved the semantics of how the exceptions propagate by raising a RunFailedError instead, for which __cause__ wraps a safe proxy for the original exception and traceback. Rejected possible solutions: reproduce the exception and traceback in the original interpreter and raise that. raise a subclass of RunFailedError that proxies the original exception and traceback. raise RuntimeError instead of RunFailedError convert at the boundary (a la subprocess.CalledProcessError ) (requires a cross-interpreter representation) support customization via Interpreter.excepthook (requires a cross-interpreter representation) wrap in a proxy at the boundary (including with support for something like err.raise() to propagate the traceback). return the exception (or its proxy) from interp.exec() instead of raising it return a result object (like subprocess does) [result-object] (unnecessary complexity?) throw the exception away and expect users to deal with unhandled exceptions explicitly in the script they pass to interp.exec() (they can pass error info out via channels); with threads you have to do something similar Always associate each new interpreter with its own thread As implemented in the C-API, an interpreter is not inherently tied to any thread. Furthermore, it will run in any existing thread, whether created by Python or not. You only have to activate one of its thread states ( PyThreadState ) in the thread first. This means that the same thread may run more than one interpreter (though obviously not at the same time). The proposed module maintains this behavior. Interpreters are not tied to threads. Only calls to Interpreter.exec() are. However, one of the key objectives of this PEP is to provide a more human-centric concurrency model. With that in mind, from a conceptual standpoint the module might be easier to understand if each interpreter were associated with its own thread. That would mean interpreters.create() would create a new thread and Interpreter.exec() would only execute in that thread (and nothing else would). The benefit is that users would not have to wrap Interpreter.exec() calls in a new threading.Thread . Nor would they be in a position to accidentally pause the current interpreter (in the current thread) while their interpreter executes. The idea is rejected because the benefit is small and the cost is high. The difference from the capability in the C-API would be potentially confusing. The implicit creation of threads is magical. The early creation of threads is potentially wasteful. The inability to run arbitrary interpreters in an existing thread would prevent some valid use cases, frustrating users. Tying interpreters to threads would require extra runtime modifications. It would also make the module’s implementation overly complicated. Finally, it might not even make the module easier to understand. Only associate interpreters upon use Associate interpreters with channel ends only once recv() , send() , etc. are called. Doing this is potentially confusing and also can lead to unexpected races where a channel is auto-closed before it can be used in the original (creating) interpreter. Allow multiple simultaneous calls to Interpreter.exec() This would make sense especially if Interpreter.exec() were to manage new threads for you (which we’ve rejected). Essentially, each call would run independently, which would be mostly fine from a narrow technical standpoint, since each interpreter can have multiple threads. The problem is that the interpreter has only one __main__ module and simultaneous Interpreter.exec() calls would have to sort out sharing __main__ or we’d have to invent a new mechanism. Neither would be simple enough to be worth doing. Add a “reraise” method to RunFailedError While having __cause__ set on RunFailedError helps produce a more useful traceback, it’s less helpful when handling the original error. To help facilitate this, we could add RunFailedError.reraise() . This method would enable the following pattern: try : try : interp . exec ( script ) except RunFailedError as exc : exc . reraise () except MyException : ... This would be made even simpler if there existed a __reraise__ protocol. All that said, this is completely unnecessary. Using __cause__ is good enough: try : try : interp . exec ( script ) except RunFailedError as exc : raise exc . __cause__ except MyException : ... Note that in extreme cases it may require a little extra boilerplate: try : try : interp . exec ( script ) except RunFailedError as exc : if exc . __cause__ is not None : raise exc . __cause__ raise # re-raise except MyException : ... Implementation The implementation of the PEP has 4 parts: the high-level module described in this PEP (mostly a light wrapper around a low-level C extension the low-level C extension module additions to the internal C-API needed by the low-level module secondary fixes/changes in the CPython runtime that facilitate the low-level module (among other benefits) These are at various levels of completion, with more done the lower you go: the high-level module has been, at best, roughly implemented. However, fully implementing it will be almost trivial. the low-level module is mostly complete. The bulk of the implementation was merged into master in December 2018 as the “_xxsubinterpreters” module (for the sake of testing multiple interpreters functionality). Only the exception propagation implementation remains to be finished, which will not require extensive work. all necessary C-API work has been finished all anticipated work in the runtime has been finished The implementation effort for PEP 554 is being tracked as part of a larger project aimed at improving multi-core support in CPython. [multi-core-project] References [ c-api ] https://docs.python.org/3/c-api/init.html#sub-interpreter-support [ CSP ] https://en.wikipedia.org/wiki/Communicating_sequential_processes https://github.com/futurecore/python-csp [ fifo ] https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Pipe https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Queue https://docs.python.org/3/library/queue.html#module-queue http://stackless.readthedocs.io/en/2.7-slp/library/stackless/channels.html https://golang.org/doc/effective_go.html#sharing http://www.jtolds.com/writing/2016/03/go-channels-are-bad-and-you-should-feel-bad/ [ caveats ] https://docs.python.org/3/c-api/init.html#bugs-and-caveats [ cryptography ] https://github.com/pyca/cryptography/issues/2299 [ gilstate ] https://bugs.python.org/issue10915 http://bugs.python.org/issue15751 [ bug-rate ] https://mail.python.org/pipermail/python-ideas/2017-September/047094.html [ benefits ] https://mail.python.org/pipermail/python-ideas/2017-September/047122.html [ reset_globals ] https://mail.python.org/pipermail/python-dev/2017-September/149545.html [ async ] https://mail.python.org/pipermail/python-dev/2017-September/149420.html https://mail.python.org/pipermail/python-dev/2017-September/149585.html [ result-object ] https://mail.python.org/pipermail/python-dev/2017-September/149562.html [ jython ] https://mail.python.org/pipermail/python-ideas/2017-May/045771.html [ multi-core-project ] https://github.com/ericsnowcurrently/multi-core-python [ cache-line-ping-pong ] https://mail.python.org/archives/list/python-dev@python.org/message/3HVRFWHDMWPNR367GXBILZ4JJAUQ2STZ/ mp-conn https://docs.python.org/3/library/multiprocessing.html#connection-objects main-thread https://mail.python.org/pipermail/python-ideas/2017-September/047144.html https://mail.python.org/pipermail/python-dev/2017-September/149566.html petr-c-ext https://mail.python.org/pipermail/import-sig/2016-June/001062.html https://mail.python.org/pipermail/python-ideas/2016-April/039748.html Copyright This document has been placed in the public domain. Source: https://github.com/python/peps/blob/main/peps/pep-0554.rst Last modified: 2025-02-01 08:55:40 GMT
#interpreters-module-api.txt
"Title: PEP 554 – Multiple Interpreters in the Stdlib | peps.python.org\n\nPEP 554 – Multiple In(...TRUNCATED)
#github-python-org.txt
"Title: PEP 512 – Migrating from hg.python.org to GitHub | peps.python.org\n\nPEP 512 – Migratin(...TRUNCATED)
#id25.txt
"Title: PEP 8002 – Open Source Governance Survey | peps.python.org\n\nPEP 8002 – Open Source Gov(...TRUNCATED)
2021#top.txt
"PSF Sponsorship Program\nYour contributions matter and they make an\nIMPACT\n. Below are some of th(...TRUNCATED)
#id68.txt
"Title: PEP 512 – Migrating from hg.python.org to GitHub | peps.python.org\n\nPEP 512 – Migratin(...TRUNCATED)
#id16.txt
"Title: PEP 8002 – Open Source Governance Survey | peps.python.org\n\nPEP 8002 – Open Source Gov(...TRUNCATED)
#toc-entry-16.txt
"Work Groups of the Python Software Foundation\nActive Work Groups\nCode of Conduct Work Group\nDive(...TRUNCATED)
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
19