Compute grad of UserExpression

In order to use grad() you have to first project your expression on a suitable function space.

try out this:

from fenics import *

class CustomExpression(UserExpression):
    def __init__(self, **kwargs):
        super().__init__(kwargs)

    def eval_cell(self, value, x, ufc_cell):
        value[0] = 1

    def value_shape(self):
        return ()

mesh = UnitSquareMesh(16, 16)
V = FunctionSpace(mesh, 'CG', 1)
n = FacetNormal(mesh)
my_expression = CustomExpression()
u = project(my_expression, V)

print(assemble(dot(grad(u), n)*ds))