Skip to content

Allow dolfinx.fem.Constant to take native float as value type - #3847

Merged
garth-wells merged 4 commits into
FEniCS:mainfrom
finsberg:allow-native-float-in-constant
Aug 18, 2025
Merged

Allow dolfinx.fem.Constant to take native float as value type#3847
garth-wells merged 4 commits into
FEniCS:mainfrom
finsberg:allow-native-float-in-constant

Conversation

@finsberg

@finsberg finsberg commented Aug 12, 2025

Copy link
Copy Markdown
Contributor

Currently mypy complains on the following code

from mpi4py import MPI
import dolfinx
import numpy as np


mesh = dolfinx.mesh.create_unit_square(MPI.COMM_WORLD, 2, 2)
x = dolfinx.fem.Constant(mesh, 1.0)

with the error

error: Argument 2 to "Constant" has incompatible type "float"; expected "ndarray[Any, Any] | Sequence[Any] | floating[Any] | complexfloating[Any, Any]"  [arg-type]

while the following works

from mpi4py import MPI
import dolfinx
import numpy as np


mesh = dolfinx.mesh.create_unit_square(MPI.COMM_WORLD, 2, 2)
x = dolfinx.fem.Constant(mesh, np.float64(1.0))

In my opinion it is quite annoying to have to wrap all floats in a numpy float, so here I am suggesting to add (native) float as a valid type to dolfinx.fem.Constant

As a side note, the main issue here is really that

import numpy as np

x: np.floating = 1.0

fails in mypy.

@finsberg finsberg changed the title Allow constant to take native float as value type Allow dolfinx.fem.Constant to take native float as value type Aug 12, 2025
Comment thread python/dolfinx/fem/function.py Outdated
finsberg and others added 2 commits August 13, 2025 20:34
Co-authored-by: Paul T. Kühner <56360279+schnellerhase@users.noreply.github.com>
@garth-wells
garth-wells added this pull request to the merge queue Aug 18, 2025
Merged via the queue into FEniCS:main with commit 855585d Aug 18, 2025
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants