Repository: sympy/sympy

Issue:
Higher order derivatives that cannot be evaluated, like re(x).diff(x, 2), raise an exception
This issue arose in a [comment on another issue]( https://github.com/sympy/sympy/issues/15457#issuecomment-436453327) but since it's actually unrelated, is posted here separately. 
```
>>> re(x).diff(x, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ubuntu/sympy/sympy/core/expr.py", line 3047, in diff
    return Derivative(self, *symbols, **assumptions)
  File "/home/ubuntu/sympy/sympy/core/function.py", line 1370, in __new__
    obj = expr._eval_derivative_n_times(v, count)
  File "/home/ubuntu/sympy/sympy/core/basic.py", line 1688, in _eval_derivative_n_times
    obj2 = obj._accept_eval_derivative(s)
AttributeError: 'NoneType' object has no attribute '_accept_eval_derivative'
```
This happens whenever a higher-order derivative is requested for a function that does not have an explicit derivative. The expected output is 
```
Derivative(re(x), (x, 2))
```
A PR is forthcoming. 


Discussion:

Patch:
diff --git a/sympy/core/basic.py b/sympy/core/basic.py
index 654eb56fd0..a134fab92b 100644
--- a/sympy/core/basic.py
+++ b/sympy/core/basic.py
@@ -1686,10 +1686,10 @@ def _eval_derivative_n_times(self, s, n):
             obj = self
             for i in range(n):
                 obj2 = obj._accept_eval_derivative(s)
-                if obj == obj2:
+                if obj == obj2 or obj2 is None:
                     break
                 obj = obj2
-            return obj
+            return obj2
         else:
             return None
 


Test patch:
diff --git a/sympy/core/tests/test_diff.py b/sympy/core/tests/test_diff.py
index bf24fde2fe..aadb1f9fc2 100644
--- a/sympy/core/tests/test_diff.py
+++ b/sympy/core/tests/test_diff.py
@@ -1,6 +1,6 @@
 from sympy import (Symbol, Rational, cos, sin, tan, cot, exp, log,
     Function, Derivative, Expr, symbols, pi, I, S, diff, Piecewise,
-    Eq, ff, Sum, And, factorial, Max, NDimArray)
+    Eq, ff, Sum, And, factorial, Max, NDimArray, re, im)
 from sympy.utilities.pytest import raises
 
 
@@ -88,6 +88,10 @@ def __new__(cls, x):
     x, y = symbols('x y')
     # My doesn't have its own _eval_derivative method
     assert My(x).diff(x).func is Derivative
+    assert My(x).diff(x, 3).func is Derivative
+    assert re(x).diff(x, 2) == Derivative(re(x), (x, 2))  # issue 15518
+    assert diff(NDimArray([re(x), im(x)]), (x, 2)) == NDimArray(
+        [Derivative(re(x), (x, 2)), Derivative(im(x), (x, 2))])
     # it doesn't have y so it shouldn't need a method for this case
     assert My(x).diff(y) == 0