Skip to content

Instantly share code, notes, and snippets.

@NoahCardoza
Created June 15, 2025 22:11
Show Gist options
  • Save NoahCardoza/5579e807dbee18cc358122f3e552ed9e to your computer and use it in GitHub Desktop.
Save NoahCardoza/5579e807dbee18cc358122f3e552ed9e to your computer and use it in GitHub Desktop.
Pin Poetry Package Versions

Poetry Pin Versions

This script will take the versions from the current lock file and pin them in the pyproject.toml file. This will keep new versions from being installed if for some reason you need to rebuild the poetry.lock file and gives you more control when upgrading packages to ensure the build isn't broken.

Usage

pip install toml
python poetry_pin_versions.py
import toml
def read_lock_file(path="poetry.lock"):
with open(path, "r") as f:
return toml.load(f)
def read_pyproject(path="pyproject.toml"):
with open(path, "r") as f:
return toml.load(f)
def write_pyproject(data, path="pyproject.toml"):
with open(path, "w") as f:
toml.dump(data, f)
def main():
# Read both files
lock_data = read_lock_file()
pyproject_data = read_pyproject()
# Create package version mapping from lock file
package_versions = {
pkg["name"]: pkg["version"]
for pkg in lock_data["package"]
}
# Update dependencies in pyproject.toml
deps = pyproject_data["tool"]["poetry"]["dependencies"]
for pkg_name in deps.keys():
if pkg_name == "python":
continue
if pkg_name in package_versions:
deps[pkg_name] = package_versions[pkg_name]
# Update dev.dependencies in pyproject.toml
dev_deps = pyproject_data["tool"]["poetry"]['group']['dev'].get("dependencies", {})
for pkg_name in dev_deps.keys():
if pkg_name == "python":
continue
if pkg_name in package_versions:
dev_deps[pkg_name] = package_versions[pkg_name]
pyproject_data["tool"]["poetry"]['group']["dev"]["dependencies"] = dev_deps
# Write updated pyproject.toml
write_pyproject(pyproject_data)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment