Thomas
Thomas

Reputation: 1215

Use poetry to create templated Python projects

Having struggled with Python package management, I have come to like Poetry. I am (mostly) able to use it without issues and installing packages is working well for me.

However, I find myself repeating the same pattern over and over again:

poetry new my_new_package
cd my_new_package
poetry add numpy pandas matplotlib rich ipython black scikit-learn scipy mypy
rm README.rst
touch README.md
git init 

I.e., there are a few packages that I always want installed, I always want to run git init, and I prefer the .md readme over the .rst one.

Oh, and I also change python = "^3.10" to python = "~3.10" in the pyproject.toml.

My wish is that I can do something like poetry from template pyproject.toml instead of all of the above. Now I get that, if I just run poetry install pyproject.toml with the pyproject.toml file from above, poetry would install all packages. But it would not create the folder structure, the readme, the git folders, etc.

Question: Is there a way to achieve what I want? Ideally, I could also have a dynamic project name, e.g. poetry from template pyproject.toml my_other_project. Is this possible with poetry? Or am I just using the wrong tool?

Thanks in advance!

Upvotes: 1

Views: 2221

Answers (2)

Andrew Dennison
Andrew Dennison

Reputation: 1089

If you are on Windows, a cmd file like the one below can be used:

Fixing up python = "^3.10" to python = "~3.10" in the pyproject.toml. is left as an exercise for the student. :)

Hint: sed or awk can be used for this sort of thing.

Note: Script ignores any arguments after the 1st one.

poetry_new.cmd:

@ECHO OFF
REM creates project with my customizations
REM handles absolute and relative paths properly

SETLOCAL EnableExtensions EnableDelayedExpansion

REM if !1 arg show usage
@IF {%1} == {} goto :Usage
@IF NOT {%2} == {} goto :Usage

SET PARENT=%~dp1
SET PROJECT=%~nx1
REM PARENT=%PARENT%, PROJECT=%PROJECT%

IF NOT EXIST "%PARENT%" (
    MKDIR "%PARENT% "
    if ERRORLEVEL 1 Goto :FAIL MKDIR %1 -- failed
)

PUSHD "%PARENT%"

poetry new "%PROJECT%"

PUSHD "%PROJECT%"

poetry remove pytest -D

REM add more customizations here:
REM poetry add pytest
REM poetry add numpy pandas matplotlib rich ipython black scikit-learn scipy mypy

RENAME README.rst README.md

REM Post poetry new
REM open explorer in newly created project folder
start /B Explorer /n,/e,.

start PyCharm "%1"

goto :EOF

:Usage
    SET ERRORLEVEL=99
    @ECHO Usage %0 new-project-name ... - creates project with my customizations
    goto :Fail Usage %0 new-project-name ... - creates project with my customizations

:Fail
@ECHO %*
PAUSE
EXIT

Upvotes: 0

finswimmer
finswimmer

Reputation: 15202

This kind of flexibility is out of scope for Poetry. Use cookiecutter instead.

Upvotes: 3

Related Questions