gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get(self, item, default=None, *args, **kwargs):
    if item not in self:  # toggle case
        item = item.lower() if item.isupper() else upperfy(item)
    return super(DynaBox, self).get(item, default, *args, **kwargs)


# Traceback (dynaconf.validator.ValidationError)
Host: localhost
Name: Jane Doe
Traceback (most recent call last):
File "/Users/rene/Downloads/Validation/test.py", line 13, in <module>
settings.validators.validate()
File "/Users/rene/.pyenv/versions/3.9.0/lib/python3.9/site-packages/dynaconf/validator.py", line 318, in validate
validator.validate(self.settings)
File "/Users/rene/.pyenv/versions/3.9.0/lib/python3.9/site-packages/dynaconf/validator.py", line 172, in validate
self._validate_items(settings, settings.current_env)
File "/Users/rene/.pyenv/versions/3.9.0/lib/python3.9/site-packages/dynaconf/validator.py", line 194, in _validate_items
raise ValidationError(
dynaconf.validator.ValidationError: Operator.Name is required in env main

# Fixed code
def get(self, item, default=None, *args, **kwargs):
    if item not in self:  # toggle case
        item = item.lower() if item.isupper() else upperfy(item)
    value = super(DynaBox, self).get(item, empty, *args, **kwargs)
    if value is empty:
        # see Issue: #486
        return self._case_insensitive_get(item, default)
    return value
# Buggy code
def try_to_load_from_py_module_name(obj, name, key=None, identifier="py", silent=False):
    """Try to load module by its string name.

    Arguments:
        obj {LAzySettings} -- Dynaconf settings instance
        name {str} -- Name of the module e.g: foo.bar.zaz

    Keyword Arguments:
        key {str} -- Single key to be loaded (default: {None})
        identifier {str} -- Name of identifier to store (default: 'py')
        silent {bool} -- Weather to raise or silence exceptions.
    """
    ctx = suppress(ImportError, TypeError) if silent else suppress()

    with ctx:
        mod = importlib.import_module(name)
        load_from_python_object(obj, mod, name, key, identifier)
        return True  # loaded ok!
    # if it reaches this point that means exception occurred, module not found.
    return False


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/kevin/.virtualenvs/pythonic-project-samples-Yf6zzgRF/lib/python3.7/site-packages/dynaconf/loaders/py_loader.py", line 61, in try_to_load_from_py_module_name
mod = importlib.import_module(name)
File "/usr/lib/python3.7/importlib/__init__.py", line 118, in import_module
if name.startswith('.'):
AttributeError: 'PosixPath' object has no attribute 'startswith'

# Fixed code
def try_to_load_from_py_module_name(obj, name, key=None, identifier="py", silent=False):
    """Try to load module by its string name.

    Arguments:
        obj {LAzySettings} -- Dynaconf settings instance
        name {str} -- Name of the module e.g: foo.bar.zaz

    Keyword Arguments:
        key {str} -- Single key to be loaded (default: {None})
        identifier {str} -- Name of identifier to store (default: 'py')
        silent {bool} -- Weather to raise or silence exceptions.
    """
    ctx = suppress(ImportError, TypeError) if silent else suppress()

    with ctx:
        mod = importlib.import_module(str(name))
        load_from_python_object(obj, mod, name, key, identifier)
        return True  # loaded ok!
    # if it reaches this point that means exception occurred, module not found.
    return False
# Buggy code
def __getitem__(self, key):
    """
    Flask templates always expects a None when key is not found in config
    """
    return self.get(key)


# Traceback (KeyError)
False
Traceback (most recent call last):
File "dc_poc/1_no_dynaconf.py", line 6, in <module>
print(app.config["NON_EXISTING"])
KeyError: 'NON_EXISTING'

# Fixed code
def __getitem__(self, key):
    try:
        return self._settings[key]
    except KeyError:
        return Config.__getitem__(self, key)
# Buggy code
def __getattr__(self, name):
    """
    First try to get value from dynaconf then from Flask
    """
    try:
        return getattr(self._settings, name)
    except AttributeError:
        return self[name]


# Traceback (KeyError)
False
Traceback (most recent call last):
File "dc_poc/1_no_dynaconf.py", line 6, in <module>
print(app.config["NON_EXISTING"])
KeyError: 'NON_EXISTING'

# Fixed code
def __getattr__(self, name):
    """
    First try to get value from dynaconf then from Flask Config
    """
    try:
        return getattr(self._settings, name)
    except AttributeError:
        return self[name]
# Buggy code
def yaml_set_comment_before_after_key(
    self, key, before=None, indent=0, after=None, after_indent=None
):
    # type: (Any, Any, Any, Any, Any) -> None
    """
    expects comment (before/after) to be without `#` and possible have multiple lines
    """
    from ruamel.yaml.error import CommentMark
    from ruamel.yaml.tokens import CommentToken

    def comment_token(s, mark):
        # type: (Any, Any) -> Any
        # handle empty lines as having no comment
        return CommentToken(("# " if s else "") + s + "\n", mark, None)

    if after_indent is None:
        after_indent = indent + 2
    if before and (len(before) > 1) and before[-1] == "\n":
        before = before[:-1]  # strip final newline if there
    if after and after[-1] == "\n":
        after = after[:-1]  # strip final newline if there
    start_mark = CommentMark(indent)
    c = self.ca.items.setdefault(key, [None, [], None, None])
    if before == "\n":
        c[1].append(comment_token("", start_mark))
    elif before:
        for com in before.split("\n"):
            c[1].append(comment_token(com, start_mark))
    if after:
        start_mark = CommentMark(after_indent)
        if c[3] is None:
            c[3] = []
        for com in after.split("\n"):
            c[3].append(comment_token(com, start_mark))  # type: ignore


# Traceback (TypeError)
# Traceback python error.py
(dynaconf) ➜  dynaconf git:(master) ✗ python error.py
Traceback (most recent call last):
File "error.py", line 5, in <module>
data = DynaBox(settings.as_dict())
TypeError: __new__() missing 1 required keyword-only argument: 'box_settings'

# Fixed code
def yaml_set_comment_before_after_key(
    self, key, before=None, indent=0, after=None, after_indent=None
):
    # type: (Any, Any, Any, Any, Any) -> None
    """
    expects comment (before/after) to be without `#` and possible have multiple lines
    """
    from dynaconf.vendor.ruamel.yaml.error import CommentMark
    from dynaconf.vendor.ruamel.yaml.tokens import CommentToken

    def comment_token(s, mark):
        # type: (Any, Any) -> Any
        # handle empty lines as having no comment
        return CommentToken(("# " if s else "") + s + "\n", mark, None)

    if after_indent is None:
        after_indent = indent + 2
    if before and (len(before) > 1) and before[-1] == "\n":
        before = before[:-1]  # strip final newline if there
    if after and after[-1] == "\n":
        after = after[:-1]  # strip final newline if there
    start_mark = CommentMark(indent)
    c = self.ca.items.setdefault(key, [None, [], None, None])
    if before == "\n":
        c[1].append(comment_token("", start_mark))
    elif before:
        for com in before.split("\n"):
            c[1].append(comment_token(com, start_mark))
    if after:
        start_mark = CommentMark(after_indent)
        if c[3] is None:
            c[3] = []
        for com in after.split("\n"):
            c[3].append(comment_token(com, start_mark))  # type: ignore
# Buggy code
def version_tnf(t1, t2=None):
    # type: (Any, Any) -> Any
    """
    return True if ruamel.yaml version_info < t1, None if t2 is specified and bigger else False
    """
    from ruamel.yaml import version_info  # NOQA

    if version_info < t1:
        return True
    if t2 is not None and version_info < t2:
        return None
    return False


# Traceback (TypeError)
# Traceback python error.py
(dynaconf) ➜  dynaconf git:(master) ✗ python error.py
Traceback (most recent call last):
File "error.py", line 5, in <module>
data = DynaBox(settings.as_dict())
TypeError: __new__() missing 1 required keyword-only argument: 'box_settings'

# Fixed code
def version_tnf(t1, t2=None):
    # type: (Any, Any) -> Any
    """
    return True if ruamel.yaml version_info < t1, None if t2 is specified and bigger else False
    """
    from dynaconf.vendor.ruamel.yaml import version_info  # NOQA

    if version_info < t1:
        return True
    if t2 is not None and version_info < t2:
        return None
    return False
# Buggy code
def construct_rt_sequence(self, node, seqtyp, deep=False):
    # type: (Any, Any, bool) -> Any
    if not isinstance(node, SequenceNode):
        raise ConstructorError(
            None,
            None,
            "expected a sequence node, but found %s" % node.id,
            node.start_mark,
        )
    ret_val = []
    if node.comment:
        seqtyp._yaml_add_comment(node.comment[:2])
        if len(node.comment) > 2:
            seqtyp.yaml_end_comment_extend(node.comment[2], clear=True)
    if node.anchor:
        from ruamel.yaml.serializer import templated_id

        if not templated_id(node.anchor):
            seqtyp.yaml_set_anchor(node.anchor)
    for idx, child in enumerate(node.value):
        if child.comment:
            seqtyp._yaml_add_comment(child.comment, key=idx)
            child.comment = None  # if moved to sequence remove from child
        ret_val.append(self.construct_object(child, deep=deep))
        seqtyp._yaml_set_idx_line_col(
            idx, [child.start_mark.line, child.start_mark.column]
        )
    return ret_val


# Traceback (TypeError)
# Traceback python error.py
(dynaconf) ➜  dynaconf git:(master) ✗ python error.py
Traceback (most recent call last):
File "error.py", line 5, in <module>
data = DynaBox(settings.as_dict())
TypeError: __new__() missing 1 required keyword-only argument: 'box_settings'

# Fixed code
def construct_rt_sequence(self, node, seqtyp, deep=False):
    # type: (Any, Any, bool) -> Any
    if not isinstance(node, SequenceNode):
        raise ConstructorError(
            None,
            None,
            "expected a sequence node, but found %s" % node.id,
            node.start_mark,
        )
    ret_val = []
    if node.comment:
        seqtyp._yaml_add_comment(node.comment[:2])
        if len(node.comment) > 2:
            seqtyp.yaml_end_comment_extend(node.comment[2], clear=True)
    if node.anchor:
        from dynaconf.vendor.ruamel.yaml.serializer import templated_id

        if not templated_id(node.anchor):
            seqtyp.yaml_set_anchor(node.anchor)
    for idx, child in enumerate(node.value):
        if child.comment:
            seqtyp._yaml_add_comment(child.comment, key=idx)
            child.comment = None  # if moved to sequence remove from child
        ret_val.append(self.construct_object(child, deep=deep))
        seqtyp._yaml_set_idx_line_col(
            idx, [child.start_mark.line, child.start_mark.column]
        )
    return ret_val
# Buggy code
def map(self, **kw):
    # type: (Any) -> Any
    if "rt" in self.typ:
        from ruamel.yaml.comments import CommentedMap

        return CommentedMap(**kw)
    else:
        return dict(**kw)


# Traceback (TypeError)
# Traceback python error.py
(dynaconf) ➜  dynaconf git:(master) ✗ python error.py
Traceback (most recent call last):
File "error.py", line 5, in <module>
data = DynaBox(settings.as_dict())
TypeError: __new__() missing 1 required keyword-only argument: 'box_settings'

# Fixed code
def map(self, **kw):
    # type: (Any) -> Any
    if "rt" in self.typ:
        from dynaconf.vendor.ruamel.yaml.comments import CommentedMap

        return CommentedMap(**kw)
    else:
        return dict(**kw)
# Buggy code
def seq(self, *args):
    # type: (Any) -> Any
    if "rt" in self.typ:
        from ruamel.yaml.comments import CommentedSeq

        return CommentedSeq(*args)
    else:
        return list(*args)


# Traceback (TypeError)
# Traceback python error.py
(dynaconf) ➜  dynaconf git:(master) ✗ python error.py
Traceback (most recent call last):
File "error.py", line 5, in <module>
data = DynaBox(settings.as_dict())
TypeError: __new__() missing 1 required keyword-only argument: 'box_settings'

# Fixed code
def seq(self, *args):
    # type: (Any) -> Any
    if "rt" in self.typ:
        from dynaconf.vendor.ruamel.yaml.comments import CommentedSeq

        return CommentedSeq(*args)
    else:
        return list(*args)
# Buggy code
def walk_tree(base, map=None):
    # type: (Any, Any) -> None
    """
    the routine here walks over a simple yaml tree (recursing in
    dict values and list items) and converts strings that
    have multiple lines to literal scalars

    You can also provide an explicit (ordered) mapping for multiple transforms
    (first of which is executed):
        map = ruamel.yaml.compat.ordereddict
        map['\n'] = preserve_literal
        map[':'] = SingleQuotedScalarString
        walk_tree(data, map=map)
    """
    from ruamel.yaml.compat import string_types
    from ruamel.yaml.compat import MutableMapping, MutableSequence  # type: ignore

    if map is None:
        map = {"\n": preserve_literal}

    if isinstance(base, MutableMapping):
        for k in base:
            v = base[k]  # type: Text
            if isinstance(v, string_types):
                for ch in map:
                    if ch in v:
                        base[k] = map[ch](v)
                        break
            else:
                walk_tree(v)
    elif isinstance(base, MutableSequence):
        for idx, elem in enumerate(base):
            if isinstance(elem, string_types):
                for ch in map:
                    if ch in elem:  # type: ignore
                        base[idx] = map[ch](elem)
                        break
            else:
                walk_tree(elem)


# Traceback (TypeError)
# Traceback python error.py
(dynaconf) ➜  dynaconf git:(master) ✗ python error.py
Traceback (most recent call last):
File "error.py", line 5, in <module>
data = DynaBox(settings.as_dict())
TypeError: __new__() missing 1 required keyword-only argument: 'box_settings'

# Fixed code
def walk_tree(base, map=None):
    # type: (Any, Any) -> None
    """
    the routine here walks over a simple yaml tree (recursing in
    dict values and list items) and converts strings that
    have multiple lines to literal scalars

    You can also provide an explicit (ordered) mapping for multiple transforms
    (first of which is executed):
        map = ruamel.yaml.compat.ordereddict
        map['\n'] = preserve_literal
        map[':'] = SingleQuotedScalarString
        walk_tree(data, map=map)
    """
    from dynaconf.vendor.ruamel.yaml.compat import string_types
    from dynaconf.vendor.ruamel.yaml.compat import MutableMapping, MutableSequence  # type: ignore

    if map is None:
        map = {"\n": preserve_literal}

    if isinstance(base, MutableMapping):
        for k in base:
            v = base[k]  # type: Text
            if isinstance(v, string_types):
                for ch in map:
                    if ch in v:
                        base[k] = map[ch](v)
                        break
            else:
                walk_tree(v)
    elif isinstance(base, MutableSequence):
        for idx, elem in enumerate(base):
            if isinstance(elem, string_types):
                for ch in map:
                    if ch in elem:  # type: ignore
                        base[idx] = map[ch](elem)
                        break
            else:
                walk_tree(elem)
# Buggy code
def __init__(self, _dict=dict, preserve=False):
    from toml.decoder import CommentValue

    super(TomlPreserveCommentEncoder, self).__init__(_dict, preserve)
    self.dump_funcs[CommentValue] = lambda v: v.dump(self.dump_value)


# Traceback (TypeError)
# Traceback python error.py
(dynaconf) ➜  dynaconf git:(master) ✗ python error.py
Traceback (most recent call last):
File "error.py", line 5, in <module>
data = DynaBox(settings.as_dict())
TypeError: __new__() missing 1 required keyword-only argument: 'box_settings'

# Fixed code
def __init__(self, _dict=dict, preserve=False):
    from dynaconf.vendor.toml.decoder import CommentValue

    super(TomlPreserveCommentEncoder, self).__init__(_dict, preserve)
    self.dump_funcs[CommentValue] = lambda v: v.dump(self.dump_value)
# Buggy code
def __init__(
    self,
    app=None,
    instance_relative_config=False,
    dynaconf_instance=None,
    **kwargs,
):
    """kwargs holds initial dynaconf configuration"""
    if not flask_installed:  # pragma: no cover
        raise RuntimeError(
            "To use this extension Flask must be installed "
            "install it with: pip install flask"
        )
    self.kwargs = kwargs

    kwargs.setdefault("ENVVAR_PREFIX", "FLASK")
    env_prefix = f"{kwargs['ENVVAR_PREFIX']}_ENV"  # FLASK_ENV
    kwargs.setdefault("ENV_SWITCHER", env_prefix)
    kwargs.setdefault("ENVIRONMENTS", True)
    kwargs.setdefault("load_dotenv", True)
    kwargs.setdefault("default_settings_paths", dynaconf.DEFAULT_SETTINGS_FILES)

    self.dynaconf_instance = dynaconf_instance
    self.instance_relative_config = instance_relative_config
    if app:
        self.init_app(app, **kwargs)


# Traceback (box.BoxKeyError)
200       # Looks OK, defined in development
BB        # Looks OK, missing in development but defined in default
DEV Namespace A    # Looks OK, defined in the development.namespace section
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/mnt/data/projects/pkh/rapidxmm/repos/backend/backend/src/.venv/lib/python3.7/site-packages/dynaconf/utils/boxing.py", line 15, in __getattr__
return super(DynaBox, self).__getattr__(n_item, *args, **kwargs)
File "/mnt/data/projects/pkh/rapidxmm/repos/backend/backend/src/.venv/lib/python3.7/site-packages/box.py", line 525, in __getattr__
raise BoxKeyError(str(err))
box.BoxKeyError: "'DynaBox' object has no attribute 'b'"

# Fixed code
def __init__(
    self,
    app=None,
    instance_relative_config=False,
    dynaconf_instance=None,
    extensions_list=False,
    **kwargs,
):
    """kwargs holds initial dynaconf configuration"""
    if not flask_installed:  # pragma: no cover
        raise RuntimeError(
            "To use this extension Flask must be installed "
            "install it with: pip install flask"
        )
    self.kwargs = kwargs

    kwargs.setdefault("ENVVAR_PREFIX", "FLASK")
    env_prefix = f"{kwargs['ENVVAR_PREFIX']}_ENV"  # FLASK_ENV
    kwargs.setdefault("ENV_SWITCHER", env_prefix)
    kwargs.setdefault("ENVIRONMENTS", True)
    kwargs.setdefault("load_dotenv", True)
    kwargs.setdefault("default_settings_paths", dynaconf.DEFAULT_SETTINGS_FILES)

    self.dynaconf_instance = dynaconf_instance
    self.instance_relative_config = instance_relative_config
    self.extensions_list = extensions_list
    if app:
        self.init_app(app, **kwargs)
# Buggy code
def init_app(self, app, **kwargs):
    """kwargs holds initial dynaconf configuration"""
    self.kwargs.update(kwargs)
    self.settings = self.dynaconf_instance or dynaconf.LazySettings(**self.kwargs)
    dynaconf.settings = self.settings  # rebind customized settings
    app.config = self.make_config(app)
    app.dynaconf = self.settings


# Traceback (box.BoxKeyError)
200       # Looks OK, defined in development
BB        # Looks OK, missing in development but defined in default
DEV Namespace A    # Looks OK, defined in the development.namespace section
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/mnt/data/projects/pkh/rapidxmm/repos/backend/backend/src/.venv/lib/python3.7/site-packages/dynaconf/utils/boxing.py", line 15, in __getattr__
return super(DynaBox, self).__getattr__(n_item, *args, **kwargs)
File "/mnt/data/projects/pkh/rapidxmm/repos/backend/backend/src/.venv/lib/python3.7/site-packages/box.py", line 525, in __getattr__
raise BoxKeyError(str(err))
box.BoxKeyError: "'DynaBox' object has no attribute 'b'"

# Fixed code
def init_app(self, app, **kwargs):
    """kwargs holds initial dynaconf configuration"""
    self.kwargs.update(kwargs)
    self.settings = self.dynaconf_instance or dynaconf.LazySettings(**self.kwargs)
    dynaconf.settings = self.settings  # rebind customized settings
    app.config = self.make_config(app)
    app.dynaconf = self.settings

    if self.extensions_list:
        if not isinstance(self.extensions_list, str):
            self.extensions_list = "EXTENSIONS"
        app.config.load_extensions(self.extensions_list)
# Buggy code
def load_extensions(self, key="EXTENSIONS", app=None):
    """Loads flask extensions dynamically."""
    app = app or self._app
    for extension in app.config[key]:
        # Split data in form `extension.path:factory_function`
        module_name, factory = extension.split(":")
        # Dynamically import extension module.
        ext = import_module(module_name)
        # Invoke factory passing app.
        getattr(ext, factory)(app)


# Traceback (box.BoxKeyError)
200       # Looks OK, defined in development
BB        # Looks OK, missing in development but defined in default
DEV Namespace A    # Looks OK, defined in the development.namespace section
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/mnt/data/projects/pkh/rapidxmm/repos/backend/backend/src/.venv/lib/python3.7/site-packages/dynaconf/utils/boxing.py", line 15, in __getattr__
return super(DynaBox, self).__getattr__(n_item, *args, **kwargs)
File "/mnt/data/projects/pkh/rapidxmm/repos/backend/backend/src/.venv/lib/python3.7/site-packages/box.py", line 525, in __getattr__
raise BoxKeyError(str(err))
box.BoxKeyError: "'DynaBox' object has no attribute 'b'"

# Fixed code
def load_extensions(self, key="EXTENSIONS", app=None):
    """Loads flask extensions dynamically."""
    app = app or self._app
    extensions = app.config.get(key)
    if not extensions:
        warnings.warn(
            f"Settings is missing {key} to load Flask Extensions",
            RuntimeWarning,
        )
        return

    for extension in app.config[key]:
        # Split data in form `extension.path:factory_function`
        module_name, factory = extension.split(":")
        # Dynamically import extension module.
        ext = import_module(module_name)
        # Invoke factory passing app.
        getattr(ext, factory)(app)
# Buggy code
def __getitem__(self, item):
    """Allow getting variables as dict keys `settings['KEY']`"""
    value = self.get(item)
    if value is None:
        raise KeyError("{0} does not exists".format(item))
    return value


# Traceback (KeyError)
Hello
Traceback (most recent call last):
File ".../dynaconf/base.py", line 222, in __getitem__
raise KeyError("{0} does not exists".format(item))
KeyError: 'nulled_name does not exists'

# Fixed code
def __getitem__(self, item):
    """Allow getting variables as dict keys `settings['KEY']`"""
    value = self.get(item, default=empty)
    if value is empty:
        raise KeyError("{0} does not exist".format(item))
    return value
# Buggy code
def write(filename, data, env=None):
    """Writes `data` to `filename` infers format by file extension."""
    loader_name = "{0}_loader".format(filename.rpartition(".")[-1])
    loader = globals().get(loader_name)
    if not loader:
        raise IOError("{0} cannot be found.".format(loader_name))

    data = DynaBox(data).to_dict()
    if env and env not in data:
        data = {env: data}

    loader.write(filename, data, merge=False)


# Traceback (KeyError)
Hello
Traceback (most recent call last):
File ".../dynaconf/base.py", line 222, in __getitem__
raise KeyError("{0} does not exists".format(item))
KeyError: 'nulled_name does not exists'

# Fixed code
def write(filename, data, env=None):
    """Writes `data` to `filename` infers format by file extension."""
    loader_name = "{0}_loader".format(filename.rpartition(".")[-1])
    loader = globals().get(loader_name)
    if not loader:
        raise IOError("{0} cannot be found.".format(loader_name))

    data = DynaBox(data).to_dict()
    if loader is not py_loader and env and env not in data:
        data = {env: data}

    loader.write(filename, data, merge=False)
# Buggy code
def write(settings_path, settings_data, merge=True):
    """Write data to a settings file.

    :param settings_path: the filepath
    :param settings_data: a dictionary with data
    :param merge: boolean if existing file should be merged with new data
    """
    settings_path = Path(settings_path)
    if settings_path.exists() and merge:  # pragma: no cover
        with io.open(
            str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
        ) as open_file:
            object_merge(toml.load(open_file), settings_data)

    with io.open(
        str(settings_path),
        "w",
        encoding=default_settings.ENCODING_FOR_DYNACONF,
    ) as open_file:
        toml.dump(settings_data, open_file)


# Traceback (KeyError)
Hello
Traceback (most recent call last):
File ".../dynaconf/base.py", line 222, in __getitem__
raise KeyError("{0} does not exists".format(item))
KeyError: 'nulled_name does not exists'

# Fixed code
def write(settings_path, settings_data, merge=True):
    """Write data to a settings file.

    :param settings_path: the filepath
    :param settings_data: a dictionary with data
    :param merge: boolean if existing file should be merged with new data
    """
    settings_path = Path(settings_path)
    if settings_path.exists() and merge:  # pragma: no cover
        with io.open(
            str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
        ) as open_file:
            object_merge(toml.load(open_file), settings_data)

    with io.open(
        str(settings_path),
        "w",
        encoding=default_settings.ENCODING_FOR_DYNACONF,
    ) as open_file:
        toml.dump(encode_nulls(settings_data), open_file)
# Buggy code
def get(self, item, default=None, *args, **kwargs):
    value = super(DynaBox, self).get(item, default, *args, **kwargs)
    if value is None or value == default:
        n_item = item.lower() if item.isupper() else upperfy(item)
        value = super(DynaBox, self).get(n_item, default, *args, **kwargs)
    return value


# Traceback (KeyError)
Hello
Traceback (most recent call last):
File ".../dynaconf/base.py", line 222, in __getitem__
raise KeyError("{0} does not exists".format(item))
KeyError: 'nulled_name does not exists'

# Fixed code
def get(self, item, default=None, *args, **kwargs):
    if item not in self:  # toggle case
        item = item.lower() if item.isupper() else upperfy(item)
    return super(DynaBox, self).get(item, default, *args, **kwargs)
# Buggy code
def write(settings_path, settings_data, merge=True):
    """Write data to a settings file.

    :param settings_path: the filepath
    :param settings_data: a dictionary with data
    :param merge: boolean if existing file should be merged with new data
    """
    if settings_path.exists() and merge:  # pragma: no cover
        object_merge(
            ConfigObj(
                io.open(
                    str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
                )
            ).dict(),
            settings_data,
        )
    new = ConfigObj()
    new.update(settings_data)
    new.write(open(str(settings_path), "bw"))


# Traceback (AttributeError)
In [1]: from dynaconf import settings

In [2]: settings.POTATO
Out[2]: 'test'

In [3]: settings.get_fresh('POTATO')

In [4]: settings.POTATO
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-22d467a777a4> in <module>
----> 1 settings.POTATO

~/miniconda3/lib/python3.7/site-packages/dynaconf/base.py in __getattr__(self, name)
95             raise AttributeError(
96                 "Attribute %s was deleted, "
---> 97                 "or belongs to different env" % name
98             )
99         if (

AttributeError: Attribute POTATO was deleted, or belongs to different env

# Fixed code
def write(settings_path, settings_data, merge=True):
    """Write data to a settings file.

    :param settings_path: the filepath
    :param settings_data: a dictionary with data
    :param merge: boolean if existing file should be merged with new data
    """
    settings_path = Path(settings_path)
    if settings_path.exists() and merge:  # pragma: no cover
        object_merge(
            ConfigObj(
                io.open(
                    str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
                )
            ).dict(),
            settings_data,
        )
    new = ConfigObj()
    new.update(settings_data)
    new.write(open(str(settings_path), "bw"))
# Buggy code
def write(settings_path, settings_data, merge=True):
    """Write data to a settings file.

    :param settings_path: the filepath
    :param settings_data: a dictionary with data
    :param merge: boolean if existing file should be merged with new data
    """

    if settings_path.exists() and merge:  # pragma: no cover
        object_merge(
            json.load(
                io.open(
                    str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
                )
            ),
            settings_data,
        )

    json.dump(
        settings_data,
        io.open(
            str(settings_path), "w", encoding=default_settings.ENCODING_FOR_DYNACONF
        ),
    )


# Traceback (AttributeError)
In [1]: from dynaconf import settings

In [2]: settings.POTATO
Out[2]: 'test'

In [3]: settings.get_fresh('POTATO')

In [4]: settings.POTATO
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-22d467a777a4> in <module>
----> 1 settings.POTATO

~/miniconda3/lib/python3.7/site-packages/dynaconf/base.py in __getattr__(self, name)
95             raise AttributeError(
96                 "Attribute %s was deleted, "
---> 97                 "or belongs to different env" % name
98             )
99         if (

AttributeError: Attribute POTATO was deleted, or belongs to different env

# Fixed code
def write(settings_path, settings_data, merge=True):
    """Write data to a settings file.

    :param settings_path: the filepath
    :param settings_data: a dictionary with data
    :param merge: boolean if existing file should be merged with new data
    """
    settings_path = Path(settings_path)
    if settings_path.exists() and merge:  # pragma: no cover
        object_merge(
            json.load(
                io.open(
                    str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
                )
            ),
            settings_data,
        )

    json.dump(
        settings_data,
        io.open(
            str(settings_path), "w", encoding=default_settings.ENCODING_FOR_DYNACONF
        ),
    )
# Buggy code
def write(settings_path, settings_data, merge=True):
    """Write data to a settings file.

    :param settings_path: the filepath
    :param settings_data: a dictionary with data
    :param merge: boolean if existing file should be merged with new data
    """
    if settings_path.exists() and merge:  # pragma: no cover
        existing = DynaconfDict()
        load(existing, str(settings_path))
        object_merge(existing, settings_data)
    with io.open(
        str(settings_path), "w", encoding=default_settings.ENCODING_FOR_DYNACONF
    ) as f:
        f.writelines(
            ["{} = {}\n".format(k.upper(), repr(v)) for k, v in settings_data.items()]
        )


# Traceback (AttributeError)
In [1]: from dynaconf import settings

In [2]: settings.POTATO
Out[2]: 'test'

In [3]: settings.get_fresh('POTATO')

In [4]: settings.POTATO
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-22d467a777a4> in <module>
----> 1 settings.POTATO

~/miniconda3/lib/python3.7/site-packages/dynaconf/base.py in __getattr__(self, name)
95             raise AttributeError(
96                 "Attribute %s was deleted, "
---> 97                 "or belongs to different env" % name
98             )
99         if (

AttributeError: Attribute POTATO was deleted, or belongs to different env

# Fixed code
def write(settings_path, settings_data, merge=True):
    """Write data to a settings file.

    :param settings_path: the filepath
    :param settings_data: a dictionary with data
    :param merge: boolean if existing file should be merged with new data
    """
    settings_path = Path(settings_path)
    if settings_path.exists() and merge:  # pragma: no cover
        existing = DynaconfDict()
        load(existing, str(settings_path))
        object_merge(existing, settings_data)
    with io.open(
        str(settings_path), "w", encoding=default_settings.ENCODING_FOR_DYNACONF
    ) as f:
        f.writelines(
            ["{} = {}\n".format(k.upper(), repr(v)) for k, v in settings_data.items()]
        )
# Buggy code
def write(settings_path, settings_data, merge=True):
    """Write data to a settings file.

    :param settings_path: the filepath
    :param settings_data: a dictionary with data
    :param merge: boolean if existing file should be merged with new data
    """
    if settings_path.exists() and merge:  # pragma: no cover
        object_merge(
            toml.load(
                io.open(
                    str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
                )
            ),
            settings_data,
        )

    toml.dump(
        settings_data,
        io.open(
            str(settings_path), "w", encoding=default_settings.ENCODING_FOR_DYNACONF
        ),
    )


# Traceback (AttributeError)
In [1]: from dynaconf import settings

In [2]: settings.POTATO
Out[2]: 'test'

In [3]: settings.get_fresh('POTATO')

In [4]: settings.POTATO
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-22d467a777a4> in <module>
----> 1 settings.POTATO

~/miniconda3/lib/python3.7/site-packages/dynaconf/base.py in __getattr__(self, name)
95             raise AttributeError(
96                 "Attribute %s was deleted, "
---> 97                 "or belongs to different env" % name
98             )
99         if (

AttributeError: Attribute POTATO was deleted, or belongs to different env

# Fixed code
def write(settings_path, settings_data, merge=True):
    """Write data to a settings file.

    :param settings_path: the filepath
    :param settings_data: a dictionary with data
    :param merge: boolean if existing file should be merged with new data
    """
    settings_path = Path(settings_path)
    if settings_path.exists() and merge:  # pragma: no cover
        object_merge(
            toml.load(
                io.open(
                    str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
                )
            ),
            settings_data,
        )

    toml.dump(
        settings_data,
        io.open(
            str(settings_path), "w", encoding=default_settings.ENCODING_FOR_DYNACONF
        ),
    )
# Buggy code
def write(settings_path, settings_data, merge=True):
    """Write data to a settings file.

    :param settings_path: the filepath
    :param settings_data: a dictionary with data
    :param merge: boolean if existing file should be merged with new data
    """
    if settings_path.exists() and merge:  # pragma: no cover
        object_merge(
            yaml.load(
                io.open(
                    str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
                )
            ),
            settings_data,
        )

    yaml.dump(
        settings_data,
        io.open(
            str(settings_path), "w", encoding=default_settings.ENCODING_FOR_DYNACONF
        ),
    )


# Traceback (AttributeError)
In [1]: from dynaconf import settings

In [2]: settings.POTATO
Out[2]: 'test'

In [3]: settings.get_fresh('POTATO')

In [4]: settings.POTATO
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-22d467a777a4> in <module>
----> 1 settings.POTATO

~/miniconda3/lib/python3.7/site-packages/dynaconf/base.py in __getattr__(self, name)
95             raise AttributeError(
96                 "Attribute %s was deleted, "
---> 97                 "or belongs to different env" % name
98             )
99         if (

AttributeError: Attribute POTATO was deleted, or belongs to different env

# Fixed code
def write(settings_path, settings_data, merge=True):
    """Write data to a settings file.

    :param settings_path: the filepath
    :param settings_data: a dictionary with data
    :param merge: boolean if existing file should be merged with new data
    """
    settings_path = Path(settings_path)
    if settings_path.exists() and merge:  # pragma: no cover
        object_merge(
            yaml.load(
                io.open(
                    str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
                )
            ),
            settings_data,
        )

    yaml.dump(
        settings_data,
        io.open(
            str(settings_path), "w", encoding=default_settings.ENCODING_FOR_DYNACONF
        ),
    )
# Buggy code
def settings_module(self):
    """Gets SETTINGS_MODULE variable"""
    settings_module = os.environ.get(
        self.ENVVAR_FOR_DYNACONF, self.SETTINGS_MODULE_FOR_DYNACONF
    )
    if settings_module != self.SETTINGS_MODULE:
        self.set("SETTINGS_MODULE", settings_module)
    return self.SETTINGS_MODULE


# Traceback (AttributeError)
development
var1_dev
var2_dev

production
Traceback (most recent call last):
File "/home/hch/PycharmProjects/dynaconf/iia/my_project/main.py", line 13, in <module>
settings.setenv('production')
File "/home/hch/.virtualenvs/dynaconf/lib/python3.6/site-packages/dynaconf/base.py", line 459, in setenv
self.execute_loaders(env=env, silent=silent, filename=filename)
File "/home/hch/.virtualenvs/dynaconf/lib/python3.6/site-packages/dynaconf/base.py", line 572, in execute_loaders
filename=filename)
File "/home/hch/.virtualenvs/dynaconf/lib/python3.6/site-packages/dynaconf/loaders/__init__.py", line 53, in settings_loader
settings_module = settings_module or obj.settings_module
File "/home/hch/.virtualenvs/dynaconf/lib/python3.6/site-packages/dynaconf/base.py", line 413, in settings_module
if settings_module != self.SETTINGS_MODULE:
AttributeError: 'Settings' object has no attribute 'SETTINGS_MODULE'

# Fixed code
def settings_module(self):
    """Gets SETTINGS_MODULE variable"""
    settings_module = os.environ.get(
        self.ENVVAR_FOR_DYNACONF, self.SETTINGS_MODULE_FOR_DYNACONF
    )
    if settings_module != getattr(self, "SETTINGS_MODULE", None):
        self.set("SETTINGS_MODULE", settings_module)
    return self.SETTINGS_MODULE
# Buggy code
def init(self, conf: ConfigTree) -> None:
    conf = conf.with_fallback(GlueExtractor.DEFAULT_CONFIG)
    self._filters = conf.get(GlueExtractor.FILTER_KEY)
    self._glue = boto3.client("glue")
    self._extract_iter: Union[None, Iterator] = None
    self._connection_name = conf.get(GlueExtractor.CONNECTION_NAME_KEY, None) or ""


# Traceback (IndexError)
Traceback (most recent call last):
File "/usr/local/Cellar/whale/v1.1.4/bin/../libexec/build_script.py", line 23, in <module>
pull()
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/utils/task_wrappers.py", line 113, in pull
task.run()
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/task/__init__.py", line 23, in run
record = self.extractor.extract()
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/extractor/glue_extractor.py", line 28, in extract
return next(self._extract_iter)
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/extractor/glue_extractor.py", line 52, in _get_extract_iter
catalog, schema, table = self._parse_location(
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/extractor/glue_extractor.py", line 91, in _parse_location
table = splits[-1]
IndexError: list index out of range

# Fixed code
def init(self, conf: ConfigTree) -> None:
    conf = conf.with_fallback(GlueExtractor.DEFAULT_CONFIG)
    self._filters = conf.get(GlueExtractor.FILTER_KEY)
    self._connection_name = conf.get(GlueExtractor.CONNECTION_NAME_KEY) or ""
    self._is_location_parsing_enabled = conf.get(
        GlueExtractor.IS_LOCATION_PARSING_ENABLED_KEY
    )
    self._glue = boto3.client("glue")
    self._extract_iter: Union[None, Iterator] = None
# Buggy code
def get_table_file_path_relative(database, cluster, schema, table):
    if cluster is not None:
        relative_file_path = TABLE_RELATIVE_FILE_PATH.format(
            database=database, cluster=cluster, schema=schema, table=table
        )
    else:
        relative_file_path = CLUSTERLESS_TABLE_RELATIVE_FILE_PATH.format(
            database=database, schema=schema, table=table
        )
    return relative_file_path


# Traceback (IndexError)
Traceback (most recent call last):
File "/usr/local/Cellar/whale/v1.1.4/bin/../libexec/build_script.py", line 23, in <module>
pull()
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/utils/task_wrappers.py", line 113, in pull
task.run()
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/task/__init__.py", line 23, in run
record = self.extractor.extract()
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/extractor/glue_extractor.py", line 28, in extract
return next(self._extract_iter)
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/extractor/glue_extractor.py", line 52, in _get_extract_iter
catalog, schema, table = self._parse_location(
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/extractor/glue_extractor.py", line 91, in _parse_location
table = splits[-1]
IndexError: list index out of range

# Fixed code
def get_table_file_path_relative(database, cluster, schema, table):
    if cluster is not None:
        relative_file_path = TABLE_RELATIVE_FILE_PATH.format(
            database=database, cluster=cluster, schema=schema, table=table
        )
    else:
        if schema is not None:
            relative_file_path = CLUSTERLESS_TABLE_RELATIVE_FILE_PATH.format(
                database=database, schema=schema, table=table
            )
        else:
            relative_file_path = SCHEMALESS_TABLE_RELATIVE_FILE_PATH.format(
                database=database, table=table
            )
    return relative_file_path
# Buggy code
def get_table_info_from_path(
    file_path,
):
    database = os.path.dirname(file_path)
    table_string = str(file_path).split(database + "/")[-1]

    database = str(database).split("/")[-1]
    table_components = table_string.split(".")
    table = table_components[-2]
    schema = table_components[-3]
    if len(table_components) == 4:
        cluster = table_components[-4]
    else:
        cluster = None
    return database, cluster, schema, table


# Traceback (IndexError)
Traceback (most recent call last):
File "/usr/local/Cellar/whale/v1.1.4/bin/../libexec/build_script.py", line 23, in <module>
pull()
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/utils/task_wrappers.py", line 113, in pull
task.run()
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/task/__init__.py", line 23, in run
record = self.extractor.extract()
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/extractor/glue_extractor.py", line 28, in extract
return next(self._extract_iter)
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/extractor/glue_extractor.py", line 52, in _get_extract_iter
catalog, schema, table = self._parse_location(
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/extractor/glue_extractor.py", line 91, in _parse_location
table = splits[-1]
IndexError: list index out of range

# Fixed code
def get_table_info_from_path(
    file_path,
):
    database = os.path.dirname(file_path)
    table_string = str(file_path).split(database + "/")[-1]

    database = str(database).split("/")[-1]
    table_components = table_string.split(".")
    table = table_components[-2]
    if len(table_components) == 4:
        cluster = table_components[-4]
        schema = table_components[-3]
    elif len(table_components) == 3:
        cluster = None
        schema = table_components[-3]
    else:
        cluster = None
        schema = None
    return database, cluster, schema, table
# Buggy code
def configure_glue_extractors(connection: ConnectionConfigSchema):
    Extractor = GlueExtractor
    extractor = Extractor()
    scope = extractor.get_scope()

    conf = ConfigFactory.from_dict(
        {
            f"{scope}.{Extractor.CONNECTION_NAME_KEY}": connection.name,
            f"{scope}.{Extractor.FILTER_KEY}": connection.filter_key,
        }
    )

    extractors = [extractor]
    return extractors, conf


# Traceback (IndexError)
Traceback (most recent call last):
File "/usr/local/Cellar/whale/v1.1.4/bin/../libexec/build_script.py", line 23, in <module>
pull()
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/utils/task_wrappers.py", line 113, in pull
task.run()
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/task/__init__.py", line 23, in run
record = self.extractor.extract()
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/extractor/glue_extractor.py", line 28, in extract
return next(self._extract_iter)
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/extractor/glue_extractor.py", line 52, in _get_extract_iter
catalog, schema, table = self._parse_location(
File "/usr/local/Cellar/whale/v1.1.4/libexec/env/lib/python3.8/site-packages/whale/extractor/glue_extractor.py", line 91, in _parse_location
table = splits[-1]
IndexError: list index out of range

# Fixed code
def configure_glue_extractors(connection: ConnectionConfigSchema):
    Extractor = GlueExtractor
    extractor = Extractor()
    scope = extractor.get_scope()

    conf = ConfigFactory.from_dict(
        {
            f"{scope}.{Extractor.CONNECTION_NAME_KEY}": connection.name,
            f"{scope}.{Extractor.FILTER_KEY}": connection.filter_key,
            f"{scope}.{Extractor.IS_LOCATION_PARSING_ENABLED_KEY}": connection.is_location_parsing_enabled,
        }
    )

    extractors = [extractor]
    return extractors, conf
# Buggy code
def selected(self) -> Gtk.TreeIter:
    (model, tree_iter) = self.selection.get_selected()
    assert tree_iter is not None
    return tree_iter


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/cschramm/src/blueman/blueman/gui/manager/ManagerMenu.py", line 249, in on_adapter_selected
self.blueman.List.set_adapter(adapter_path)
File "/home/cschramm/src/blueman/blueman/gui/DeviceList.py", line 245, in set_adapter
self.clear()
File "/home/cschramm/src/blueman/blueman/gui/DeviceList.py", line 354, in clear
self.device_remove_event(device)
File "/home/cschramm/src/blueman/blueman/gui/manager/ManagerDeviceList.py", line 233, in device_remove_event
super().device_remove_event(device)
File "/home/cschramm/src/blueman/blueman/gui/DeviceList.py", line 237, in device_remove_event
if self.compare(self.selected(), tree_iter):
File "/home/cschramm/src/blueman/blueman/gui/GenericList.py", line 64, in selected
assert tree_iter is not None
AssertionError

# Fixed code
def selected(self) -> Optional[Gtk.TreeIter]:
    (model, tree_iter) = self.selection.get_selected()
    return tree_iter