Search code examples
python-poetry

How to change default `pyproject.toml` that is generated when running `poetry new`


When I run poetry new [directory] it generates a pyproject.toml in the directory but I always find that I make the same initial changes to it such as

  • the python version (from 2.7 to 3.8)
  • the pytest version (from 4.6 to 5.4)

How can I change these defaults so that when I run poetry new python and pytest will have my desired versions?

Is the python version specified in the pyproject.toml based on the system's python version? If that is the case, I don't think I can change my system's python version since I am using a mac and it might mess up my OS. Or can I?


Solution

  • The standard way to create project templates in python is with the cookiecutter utility. Its documentation is quite good and you can get started creating your own templates easily, but I'll give a short intro using the example you gave.

    Cookiecutter uses a template language that allows you to specify which parts of your project template can be parametrized. In your case, that would be the project name (freely choosable) and maybe also the python & pytest versions (from a list of values). This information will be stored in a file called cookiecutter.json (some more examples on how that file can look here), that should look more or less like this:

    {
        "full_name": "<your name>",
        "email": "<your name>@<email>.com",
        "project_name": "default",
        "version": "0.1.0",
        "python_version": ["3.8", "2.7"],
        "pytest_version": ["5.4", "4.6"]
    }
    

    Now you need to:

    • run poetry new my_cookie to create the base for the template
    • put the cookiecutter.json into the resulting folder
    • replace all mentions of the project name under the top-level folder with {{cookiecutter.project_name}}, including files and directories
    • repeat that step for all other parameters in cookiecutter.json
    • if you're done, create a project from your template by running cookiecutter path/to/my_cookie
    • if you get stuck, take a look at this sample project template or the docs I linked for guidance