# Buggy code
def __init__(self, module=None):
    self.title = "Overview"
    self.parts = []
    self.parts_by_slug = {}
    self.doc_dir = None
    self.xml_data_file = None
    self.tex_data_file = None
    self.latex_file = None
    self.symbols = {}
    if module is None:
        return

    import importlib

    # Load the module and verifies it is a pymathics module
    try:
        self.pymathicsmodule = importlib.import_module(module)
    except ImportError:
        print("Module does not exist")
        mainfolder = ""
        self.pymathicsmodule = None
        self.parts = []
        return

    if hasattr(self.pymathicsmodule, "pymathics_version_data"):
        mainfolder = self.pymathicsmodule.__path__[0]
        self.name = self.pymathicsmodule.pymathics_version_data["name"]
        self.version = self.pymathicsmodule.pymathics_version_data["version"]
        self.author = self.pymathicsmodule.pymathics_version_data["author"]
    else:
        print(module + " is not a pymathics module.")
        mainfolder = ""
        self.pymathicsmodule = None
        self.parts = []
        return

    # Paths
    self.doc_dir = self.pymathicsmodule.__path__[0] + "/doc/"
    self.xml_data_file = self.doc_dir + "xml/data"
    self.tex_data_file = self.doc_dir + "tex/data"
    self.latex_file = self.doc_dir + "tex/documentation.tex"

    # Load the dictionary of mathics symbols defined in the module
    self.symbols = {}
    from mathics.builtin import is_builtin, Builtin

    print("loading symbols")
    for name in dir(self.pymathicsmodule):
        var = getattr(self.pymathicsmodule, name)
        if (
            hasattr(var, "__module__")
            and var.__module__ != "mathics.builtin.base"
            and is_builtin(var)
            and not name.startswith("_")
            and var.__module__[: len(self.pymathicsmodule.__name__)]
            == self.pymathicsmodule.__name__
        ):  # nopep8
            instance = var(expression=False)
            if isinstance(instance, Builtin):
                self.symbols[instance.get_name()] = instance
    # Defines de default first part, in case we are building an independent documentation module.
    self.title = "Overview"
    self.parts = []
    self.parts_by_slug = {}
    try:
        files = listdir(self.doc_dir)
        files.sort()
    except FileNotFoundError:
        self.doc_dir = ""
        self.xml_data_file = ""
        self.tex_data_file = ""
        self.latex_file = ""
        files = []
    appendix = []
    for file in files:
        part_title = file[2:]
        if part_title.endswith(".mdoc"):
            part_title = part_title[: -len(".mdoc")]
            part = DocPart(self, part_title)
            text = open(self.doc_dir + file, "rb").read().decode("utf8")
            text = filter_comments(text)
            chapters = CHAPTER_RE.findall(text)
            for title, text in chapters:
                chapter = DocChapter(part, title)
                text += '<section title=""></section>'
                sections = SECTION_RE.findall(text)
                for pre_text, title, text in sections:
                    if not chapter.doc:
                        chapter.doc = Doc(pre_text)
                    if title:
                        section = DocSection(chapter, title, text)
                        chapter.sections.append(section)
                part.chapters.append(chapter)
            if file[0].isdigit():
                self.parts.append(part)
            else:
                part.is_appendix = True
                appendix.append(part)

    # Builds the automatic documentation
    builtin_part = DocPart(self, "Pymathics Modules", is_reference=True)
    title, text = get_module_doc(self.pymathicsmodule)
    chapter = DocChapter(builtin_part, title, Doc(text))
    for name in self.symbols:
        instance = self.symbols[name]
        installed = True
        for package in getattr(instance, "requires", []):
            try:
                importlib.import_module(package)
            except ImportError:
                installed = False
                break
        section = DocSection(
            chapter,
            strip_system_prefix(name),
            instance.__doc__ or "",
            operator=instance.get_operator(),
            installed=installed,
        )
        chapter.sections.append(section)
    builtin_part.chapters.append(chapter)
    self.parts.append(builtin_part)
    # Adds possible appendices
    for part in appendix:
        self.parts.append(part)

    # set keys of tests
    for tests in self.get_tests():
        for test in tests.tests:
            test.key = (tests.part, tests.chapter, tests.section, test.index)


# Traceback (KeyError)
$ mathicsserver
warning: database file /home/pablo/.local/var/mathics/mathics.sqlite not found

Migrating database /home/pablo/.local/var/mathics/mathics.sqlite
Traceback (most recent call last):
File "/home/pablo/Documents/Mathics/mathics/manage.py", line 13, in <module>
execute_from_command_line(sys.argv)
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute
self.check()
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 65, in _run_checks
issues.extend(super()._run_checks(**kwargs))
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "/home/pablo/.local/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/pablo/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 571, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/pablo/.local/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/pablo/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 564, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/pablo/Documents/Mathics/mathics/urls.py", line 14, in <module>
url(r'^', include('mathics.web.urls')),
File "/home/pablo/.local/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/pablo/Documents/Mathics/mathics/web/urls.py", line 6, in <module>
from mathics.web.views import query, main_view, login, logout, save, open, get_worksheets, doc_search, doc_part, doc_chapter, doc_section, doc
File "/home/pablo/Documents/Mathics/mathics/web/views.py", line 28, in <module>
documentation.load_pymathics_doc()
File "/home/pablo/Documents/Mathics/mathics/doc/doc.py", line 727, in load_pymathics_doc
pymathicsdoc = PyMathicsDocumentation(pymmodule)
File "/home/pablo/Documents/Mathics/mathics/doc/doc.py", line 765, in __init__
self.name = self.pymathicsmodule.pymathics_version_data['name']
KeyError: 'name'
error: failed to create database

# Fixed code
def __init__(self, module=None):
    self.title = "Overview"
    self.parts = []
    self.parts_by_slug = {}
    self.doc_dir = None
    self.xml_data_file = None
    self.tex_data_file = None
    self.latex_file = None
    self.symbols = {}
    if module is None:
        return

    import importlib

    # Load the module and verifies it is a pymathics module
    try:
        self.pymathicsmodule = importlib.import_module(module)
    except ImportError:
        print("Module does not exist")
        mainfolder = ""
        self.pymathicsmodule = None
        self.parts = []
        return

    try:
        mainfolder = self.pymathicsmodule.__path__[0]
        self.name = self.pymathicsmodule.pymathics_version_data["name"]
        self.version = self.pymathicsmodule.pymathics_version_data["version"]
        self.author = self.pymathicsmodule.pymathics_version_data["author"]
    except (AttributeError, KeyError, IndexError):
        print(module + " is not a pymathics module.")
        mainfolder = ""
        self.pymathicsmodule = None
        self.parts = []
        return

    # Paths
    self.doc_dir = self.pymathicsmodule.__path__[0] + "/doc/"
    self.xml_data_file = self.doc_dir + "xml/data"
    self.tex_data_file = self.doc_dir + "tex/data"
    self.latex_file = self.doc_dir + "tex/documentation.tex"

    # Load the dictionary of mathics symbols defined in the module
    self.symbols = {}
    from mathics.builtin import is_builtin, Builtin

    print("loading symbols")
    for name in dir(self.pymathicsmodule):
        var = getattr(self.pymathicsmodule, name)
        if (
            hasattr(var, "__module__")
            and var.__module__ != "mathics.builtin.base"
            and is_builtin(var)
            and not name.startswith("_")
            and var.__module__[: len(self.pymathicsmodule.__name__)]
            == self.pymathicsmodule.__name__
        ):  # nopep8
            instance = var(expression=False)
            if isinstance(instance, Builtin):
                self.symbols[instance.get_name()] = instance
    # Defines de default first part, in case we are building an independent documentation module.
    self.title = "Overview"
    self.parts = []
    self.parts_by_slug = {}
    try:
        files = listdir(self.doc_dir)
        files.sort()
    except FileNotFoundError:
        self.doc_dir = ""
        self.xml_data_file = ""
        self.tex_data_file = ""
        self.latex_file = ""
        files = []
    appendix = []
    for file in files:
        part_title = file[2:]
        if part_title.endswith(".mdoc"):
            part_title = part_title[: -len(".mdoc")]
            part = DocPart(self, part_title)
            text = open(self.doc_dir + file, "rb").read().decode("utf8")
            text = filter_comments(text)
            chapters = CHAPTER_RE.findall(text)
            for title, text in chapters:
                chapter = DocChapter(part, title)
                text += '<section title=""></section>'
                sections = SECTION_RE.findall(text)
                for pre_text, title, text in sections:
                    if not chapter.doc:
                        chapter.doc = Doc(pre_text)
                    if title:
                        section = DocSection(chapter, title, text)
                        chapter.sections.append(section)
                part.chapters.append(chapter)
            if file[0].isdigit():
                self.parts.append(part)
            else:
                part.is_appendix = True
                appendix.append(part)

    # Builds the automatic documentation
    builtin_part = DocPart(self, "Pymathics Modules", is_reference=True)
    title, text = get_module_doc(self.pymathicsmodule)
    chapter = DocChapter(builtin_part, title, Doc(text))
    for name in self.symbols:
        instance = self.symbols[name]
        installed = True
        for package in getattr(instance, "requires", []):
            try:
                importlib.import_module(package)
            except ImportError:
                installed = False
                break
        section = DocSection(
            chapter,
            strip_system_prefix(name),
            instance.__doc__ or "",
            operator=instance.get_operator(),
            installed=installed,
        )
        chapter.sections.append(section)
    builtin_part.chapters.append(chapter)
    self.parts.append(builtin_part)
    # Adds possible appendices
    for part in appendix:
        self.parts.append(part)

    # set keys of tests
    for tests in self.get_tests():
        for test in tests.tests:
            test.key = (tests.part, tests.chapter, tests.section, test.index)