Relative import of self or parent package?

I occasionally want to do something like this: import .. as parent or: import . as self The pattern is a little less useful for namespace packages (which I've been trying to use almost exclusively, along with relative imports) than it is for __init__.py based packages, but there is still some utility. Is there a reason one can't import dots directly and bind them to a name? I did not find any text around this and the closest I've come up with is: from .. import __name__ as parent_module_name parent = __import__(parent_module_name) Could we support relative imports without `from` so long as there is an `as`? Thanks, -- C Anthony

On 7 April 2017 at 01:53, C Anthony Risinger <anthony@xtfx.me> wrote:
Mainly the fact that globals() already covers most use cases for module self references, and even when it doesn't the above are (for a typical module) still only a few lines long: import sys self = sys.modules[__name__] and: import sys parent_name, __, __ = __name__.rpartition(".") parent = sys.modules[parent_name] Getting a reference to the current module or a parent module is also considered a sufficiently niche requirement that understanding the existence and behaviour of the sys.modules cache is considered an acceptable barrier to entry, over adding yet another variant of the import statement syntax. It's definitely a case of "Hasn't been considered worth the extra language complexity so far" rather than "couldn't be done", though - the requirement to be met would be to establish that the use cases for self and parent references are sufficiently common that they're deserving of dedicated syntactic support on par with that already offered for peer module references. Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia

On 7 April 2017 at 01:53, C Anthony Risinger <anthony@xtfx.me> wrote:
Mainly the fact that globals() already covers most use cases for module self references, and even when it doesn't the above are (for a typical module) still only a few lines long: import sys self = sys.modules[__name__] and: import sys parent_name, __, __ = __name__.rpartition(".") parent = sys.modules[parent_name] Getting a reference to the current module or a parent module is also considered a sufficiently niche requirement that understanding the existence and behaviour of the sys.modules cache is considered an acceptable barrier to entry, over adding yet another variant of the import statement syntax. It's definitely a case of "Hasn't been considered worth the extra language complexity so far" rather than "couldn't be done", though - the requirement to be met would be to establish that the use cases for self and parent references are sufficiently common that they're deserving of dedicated syntactic support on par with that already offered for peer module references. Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
participants (2)
-
C Anthony Risinger
-
Nick Coghlan