0

I know this is allowed in Python2

from module1 import *
from module2 import *
...

I was wondering if there was a way I could do the same in one line. Doesn't look like this is allowed :

from module1, module2 ... import *

I don't want something like

import module1, module2 ...

because that would need me to access functions like

module_name.function_name(...)

I want to access them directly by name. If this has been asked before, please do point me in the right direction. Thanks a lot !

Ashish Gaurav
  • 265
  • 1
  • 2
  • 11
  • 2
    This is a personal opinion, but I wouldn't recommend neither importing everything from a module, nor mixing multiple imports in one line. – jcollado Nov 12 '15 at 12:06
  • 1
    this might solve your question http://stackoverflow.com/questions/3260599/how-do-to-multiple-imports-in-python but i agree with @jcollado – 0xtvarun Nov 12 '15 at 12:08
  • thanks, that was helpful - but I completely agree with not importing everything - we can have same function names in different modules and that would cause problems. In my case, I was just curious. – Ashish Gaurav Nov 12 '15 at 12:09
  • You *do* want to access functions as `modulename.functionname` but you *don't* want to type that long `modulename` over and over again. Use `import modulename as mn` and you get the clarity of a short "prefix" (`mn.`) that you can choose yourself, and no imported name clashes. See below. – nigel222 Nov 12 '15 at 13:54
  • Importing modules with some other names does make it short, but I still have to prefix the function with the shortened name. I agree to everything you say about bad practice (not doing from ... import *) but I figure I'll wait some more time for something elegant, and probably a one liner. – Ashish Gaurav Nov 12 '15 at 15:37

2 Answers2

2

I really advise you not to import *

  • for module1 we have className1
  • for module2 we have className1

And then name conflict!!

Recommend

import pandas as pd
import numpy as np
suiwenfeng
  • 1,865
  • 1
  • 25
  • 32
  • 1
    Yes, `import longname as sn` is the way to go. This also frees the author of the module to use short but memorable names for his entities without feeling that they'll cause name collision grief. Explicit but not verbose. In other languages one often sees prefixes (as in `xx_name`) because one can't use `import modulename as xx`. – nigel222 Nov 12 '15 at 13:49
2

I would recommend against from module import * in general and definitely against doing doing them all in a single line. Just for fun, you could do it like this:

from itertools import chain
modnames = 'os sys pandas collections'.split()
locals().update(chain.from_iterable(__import__(modname).__dict__.iteritems() for modname in modnames))
Colin
  • 2,087
  • 14
  • 16