Question

Is there a way to use the from X import Y as Z idiom on a multiline import?

Specifically, I want to write something like from some.very.long.package.name import LongName as OtherLongName. The whole thing does not fit in one line.

So I tried to write it using parentheses to cross lines, but I found some strange behavior with the as keyword. Specifically:

#this is just fine
from os import (
  path)

#this is a syntax error
from os import (
  path) as os_path

The only way I have figured out to do what I want is therefore:

from some.very.long.package.name import (
  LongName)
OtherLongName = LongName

Is there any way to do it in one statement?

Was it helpful?

Solution

Add a slash where you want to stop:

from some.very.long.package.name import \
                 LongName as OtherLongName

Without it Python will think the line is over and throw SyntaxError.

You can also use importlib.import_module if you find operations on strings more convenient:

from importlib import import_module
OtherLongName = import_module('some.very.long.package.name.LongName')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top