Skip to content

do not import petsc4py.PETSc until we really need it.#256

Merged
JHopeCollins merged 3 commits intomasterfrom
JHopeCollins/delay-petsc-import
Apr 21, 2026
Merged

do not import petsc4py.PETSc until we really need it.#256
JHopeCollins merged 3 commits intomasterfrom
JHopeCollins/delay-petsc-import

Conversation

@JHopeCollins
Copy link
Copy Markdown
Contributor

When pyadjoint is imported we were checking if petsc4py.PETSc was available in the TAOSolver file whether or not the user ever actually used the TAOSolver.

The problem is that import petsc4py.PETSc will run petsc4py.init if it hasn't already been run, but it won't pass sys.argv.
This means that any PETSc options from the command line will silently be ignored. They won't even be shown by -options_left because PETSc never knew they even existed.

This PR delays importing petsc4py.PETSc and petsctools until they are actually needed so that the user has the chance to call petsc4py.init as they see fit.

@JHopeCollins JHopeCollins self-assigned this Apr 16, 2026
@JHopeCollins JHopeCollins added the bug Something isn't working label Apr 16, 2026
@JHopeCollins
Copy link
Copy Markdown
Contributor Author

@jrmaddison this doesn't change anything with the top level pyadjoint namespace, but it means that pyadjoint.optimization.tao_solver.PETSc and pyadjoint.optimization.tao_solver._reasons no longer exist so I just wanted to check if you were relying on either of them being there.

Comment thread pyadjoint/optimization/tao_solver.py Outdated
@jrmaddison
Copy link
Copy Markdown
Contributor

Seems fine to move _tao_reasons, ideally might be moved to petsctools. A module level __getattr__ would also work for PETSc, petsctools, _tao_reasons, although as mentioned per function imports also seems fine.

@JHopeCollins
Copy link
Copy Markdown
Contributor Author

Seems fine to move _tao_reasons, ideally might be moved to petsctools.

This is true, I forgot I had this old PR I didn't get around to finishing: firedrakeproject/petsctools#12

@JHopeCollins JHopeCollins merged commit dc20b92 into master Apr 21, 2026
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants