0

Why can't I make a short cut name for a module and use that module to import things?

For example:

import utils.utils as utils
print(utils)
print(utils.make_and_check_dir)

From the print statement we can see that the utils package does indeed have my function but then the following import fails (confusingly to me):

from utils import make_and_check_dir

Why? Is there no way to make a short hand for:

pkg.module

?


Error msg:

<module 'utils.utils' from '/Users/pinocchio/git_project/project/utils/utils.py'>
<function make_and_check_dir at 0x11a428ea0>
Traceback (most recent call last):
  File "code.py", line 10, in <module>
    from utils import make_and_check_dir
ImportError: cannot import name 'make_and_check_dir' from 'utils' (/Users/pinocchio/git_project/project/utils/__init__.py)
Kermit
  • 4,922
  • 4
  • 42
  • 74
Charlie Parker
  • 5,884
  • 57
  • 198
  • 323

2 Answers2

1

My guess as to why would be that it is a namespace issue. If the capability you described were allowed maybe there could be some issue with calling "utils.make_and_check_dir" and "make_and_check_dir" on its own; maybe there would be some mapping issue, but I'm not sure.

Making a shorthand is pretty simple:

shorthand = utils.make_and_check_dir

So now you can call shorthand in place of utils.make_and_check_dir, passing the same arguments you would to the original function.

Kermit
  • 4,922
  • 4
  • 42
  • 74
Davenporten
  • 323
  • 2
  • 13
1

Actually what you are doing is right, "alias" using "as". So I think error should be from your modules, like utils could be a function or class rather than being a module. Maybe, try changing names (it avoids confusion and you can figure out the error) of utils and its child utils.

Try reading - 1. http://docs.python.org/reference/simple_stmts.html#import 2. Can you define aliases for imported modules in Python? This could help you find out any silly mistake, if you had done... :)

Ok I got it I think.

First case :
>>> import X.Y as Z
>>> Z.F1 
#No Error
>>> from Z import F1
#ModuleNotFoundError

Second case :
>>> import X.Y as X
>>> from X import F1
#Import Error

So actually, what happens is a namespace collision. When you set an alias like that in 1, Python searches for a module named Z instead of looking at its already declared alias Z. In case 2, the name X clashes with your package X and Python is confused if that "X" is your package or declared variable... so the bitter moral is, don't use such clashing names. And its better to declare full alias like "import X.Y.Z as myshortZ".

J Arun Mani
  • 620
  • 3
  • 20
  • I will read that. My utils is a folder (so I think its called the package). Then it has a python file called utils (which I assume its called a module) with the function giving me the error... – Charlie Parker Aug 23 '19 at 18:41