def package(qualified_name):
    """Return the enclosing package name where qualified_name is located.

    `qualified_name` can be a module inside the package or even an object
    inside the module. If a package name itself is provided it is returned.

    """
    try:
        module = __import__(qualified_name, fromlist=[''])
    except ImportError:
        if '.' in qualified_name:
            qualified_name, attr_name = qualified_name.rsplit('.', 1)
            module = __import__(qualified_name, fromlist=[attr_name])
        else:
            raise
    if module.__package__ is not None:
        return module.__package__
    else:
        assert module.__name__ == qualified_name
        return qualified_name
