Write Function to file at multiple time steps

Hello,
In the following minimal working example, I change the analytical expression which I assign to the function v and then print v to file at each step

from __future__ import print_function
from fenics import *
import time


mesh = UnitSquareMesh(96, 96)
V = FunctionSpace(mesh, "Lagrange", 1)
v  = Function( V )
expr = Expression("p + pow(pow(pow(x[0], 2) + pow(x[1], 2), 0.5) , 2)", degree = 4, p = 1.0)

xdmffile_v = XDMFFile( 'v.xdmf' )

for step in range(10):

    print("\n* step = ", step, "\n")

    expr.p = step
    v = interpolate( expr, V )
    xdmffile_v.write( v, step )

When opening v.xdmf with Paraview, I see an odd (?) appearing when I switch from time 0 to time 1, see screenshot

and times 1, 2, … are not shown.

What am I doing wrong?

Also, what is the correct way to write to file all snapshots of v in order to be able to visualize them even if the code is killed or crashes?
Say, for example, that the loop is killed at step = 100: If I open with Paraview the file v.xdmf written by the minimal working example, Paraview crashes.

Create your function v outside the loop,

v = Function(V)
for step in range (10):
    v.interpolate(expr)

I create the function outside the loop, see the original post.

I should use v.interpolate(expr) rather than v.interpolate(expr, V) as in the original post ? Why ?

because v is defined in the function space V, and thus you are interpolating into v.

This is unclear. Here one adds V as a second argument in interpolate

v = Expression("sin(pi*x[0])")
V = FunctionSpace(mesh, "Lagrange", 1)
Iv = interpolate(v, V)

Which is the same command lines that I used in the original post, but it does not work (see the (?) in Paraview).

Dear @mekong. You are talking about two different functions.

The one you are referring to is:
https://bitbucket.org/fenics-project/dolfin/src/1c52e837eb54cc34627f90bde254be4aa8a2ae17/python/dolfin/fem/interpolation.py?at=master#interpolation.py-31,54,71,73
while I am talking about
https://bitbucket.org/fenics-project/dolfin/src/1c52e837eb54cc34627f90bde254be4aa8a2ae17/python/dolfin/function/function.py?at=master#lines-379
which interpolates an expression into the already defined function v.

The approach you are using creates a new function at each time step. Each function is given a new name (if you don’t give it an explicit name yourself), thus when outputted to paraview each time step has a unique function.

Oh I see, thank you for your reply!