# Buggy code
def apply(self, url, elements, evaluation):
    "FetchURL[url_String, elements_]"

    import tempfile
    import os

    py_url = url.get_string_value()

    temp_handle, temp_path = tempfile.mkstemp(suffix="")
    try:
        with urllib2.urlopen(py_url) as f:
            content_type = f.info().get_content_type()
            os.write(temp_handle, f.read())

        def determine_filetype():
            return mimetype_dict.get(content_type)

        result = Import._import(temp_path, determine_filetype, elements, evaluation)
    except HTTPError as e:
        evaluation.message(
            "FetchURL",
            "httperr",
            url,
            "the server returned an HTTP status code of %s (%s)"
            % (e.code, str(e.reason)),
        )
        return Symbol("$Failed")
    except URLError as e:  # see https://docs.python.org/3/howto/urllib2.html
        if hasattr(e, "reason"):
            evaluation.message("FetchURL", "httperr", url, str(e.reason))
        elif hasattr(e, "code"):
            evaluation.message(
                "FetchURL", "httperr", url, "server returned %s" % e.code
            )
        return Symbol("$Failed")
    except ValueError as e:
        evaluation.message("FetchURL", "httperr", url, str(e))
        return Symbol("$Failed")
    finally:
        os.unlink(temp_path)

    return result


# Traceback (AttributeError)
In[1]:= Import["https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"]
Traceback (most recent call last):
File "/home/angus/venv_pypy/bin/mathics", line 11, in <module>
load_entry_point('Mathics', 'console_scripts', 'mathics')()
File "/home/angus/Mathics/mathics/main.py", line 286, in main
result = evaluation.evaluate(query, timeout=settings.TIMEOUT)
File "/home/angus/Mathics/mathics/core/evaluation.py", line 257, in evaluate
result = run_with_timeout(evaluate, timeout)
File "/home/angus/Mathics/mathics/core/evaluation.py", line 76, in run_with_timeout
return request()
File "/home/angus/Mathics/mathics/core/evaluation.py", line 240, in evaluate
result = query.evaluate(self)
File "/home/angus/Mathics/mathics/core/expression.py", line 868, in evaluate
return result.evaluate(evaluation)
File "/home/angus/Mathics/mathics/core/expression.py", line 868, in evaluate
return result.evaluate(evaluation)
File "/home/angus/Mathics/mathics/core/expression.py", line 862, in evaluate
result = rule.apply(new, evaluation, fully=False)
File "/home/angus/Mathics/mathics/core/rules.py", line 73, in apply
yield_match, expression, {}, evaluation, fully=fully)
File "/home/angus/Mathics/mathics/core/pattern.py", line 206, in match
yield_head, expression.get_head(), vars, evaluation)
File "/home/angus/Mathics/mathics/core/pattern.py", line 135, in match
yield_func(vars, None)
File "/home/angus/Mathics/mathics/core/pattern.py", line 198, in yield_head
yield_choice, expression, attributes, head_vars)
File "/home/angus/Mathics/mathics/core/pattern.py", line 321, in get_pre_choices
yield_func(vars)
File "/home/angus/Mathics/mathics/core/pattern.py", line 187, in yield_choice
wrap_oneid=expression.get_head_name() != 'System`MakeBoxes')
File "/home/angus/Mathics/mathics/core/pattern.py", line 478, in match_leaf
include_flattened=include_flattened)
File "/home/angus/Mathics/mathics/core/pattern.py", line 342, in get_wrappings
yield_func(items[0])
File "/home/angus/Mathics/mathics/core/pattern.py", line 474, in yield_wrapping
leaf_count=leaf_count, wrap_oneid=wrap_oneid)
File "/home/angus/Mathics/mathics/builtin/patterns.py", line 768, in match
self.pattern.match(yield_func, expression, new_vars, evaluation)
File "/home/angus/Mathics/mathics/builtin/patterns.py", line 951, in match
yield_func(vars, None)
File "/home/angus/Mathics/mathics/core/pattern.py", line 466, in match_yield
leaf_count=leaf_count, wrap_oneid=wrap_oneid)
File "/home/angus/Mathics/mathics/core/pattern.py", line 478, in match_leaf
include_flattened=include_flattened)
File "/home/angus/Mathics/mathics/core/pattern.py", line 342, in get_wrappings
yield_func(items[0])
File "/home/angus/Mathics/mathics/core/pattern.py", line 474, in yield_wrapping
leaf_count=leaf_count, wrap_oneid=wrap_oneid)
File "/home/angus/Mathics/mathics/builtin/patterns.py", line 768, in match
self.pattern.match(yield_func, expression, new_vars, evaluation)
File "/home/angus/Mathics/mathics/builtin/patterns.py", line 953, in match
yield_func(vars, None)
File "/home/angus/Mathics/mathics/core/pattern.py", line 469, in match_yield
yield_func(new_vars, items_rest)
File "/home/angus/Mathics/mathics/core/pattern.py", line 458, in leaf_yield
(rest_expression[0] + items_rest[0], next_rest[1]))
File "/home/angus/Mathics/mathics/core/rules.py", line 39, in yield_match
new_expression = self.do_replace(vars, options, evaluation)
File "/home/angus/Mathics/mathics/core/rules.py", line 131, in do_replace
return self.function(evaluation=evaluation, **vars_noctx)
File "/home/angus/Mathics/mathics/builtin/importexport.py", line 393, in apply
with urllib2.urlopen(py_url) as f:
AttributeError: addinfourl instance has no attribute '__enter__'

# Fixed code
def apply(self, url, elements, evaluation):
    "FetchURL[url_String, elements_]"

    import tempfile
    import os

    py_url = url.get_string_value()

    temp_handle, temp_path = tempfile.mkstemp(suffix="")
    try:
        f = urllib2.urlopen(py_url)
        try:
            if sys.version_info >= (3, 0):
                content_type = f.info().get_content_type()
            else:
                content_type = f.headers["content-type"]

            os.write(temp_handle, f.read())
        finally:
            f.close()

        def determine_filetype():
            return mimetype_dict.get(content_type)

        result = Import._import(temp_path, determine_filetype, elements, evaluation)
    except HTTPError as e:
        evaluation.message(
            "FetchURL",
            "httperr",
            url,
            "the server returned an HTTP status code of %s (%s)"
            % (e.code, str(e.reason)),
        )
        return Symbol("$Failed")
    except URLError as e:  # see https://docs.python.org/3/howto/urllib2.html
        if hasattr(e, "reason"):
            evaluation.message("FetchURL", "httperr", url, str(e.reason))
        elif hasattr(e, "code"):
            evaluation.message(
                "FetchURL", "httperr", url, "server returned %s" % e.code
            )
        return Symbol("$Failed")
    except ValueError as e:
        evaluation.message("FetchURL", "httperr", url, str(e))
        return Symbol("$Failed")
    finally:
        os.unlink(temp_path)

    return result