1

I am following this example on how to package a python module. But installing my built package with pip, when I tried to use it, while the following works.

from towel_stuff import towel_utils

x = towel_utils.has_towel()
print(x)

And this also works,

import towel_stuff.towel_utils

x = towel_stuff.towel_utils.has_towel()
print(x)

I don't understand, why the following doesn't work.

import towel_stuff

x = towel_stuff.towel_utils.has_towel()
print(x)

Normally, for example if we want to use os.path, we don't need to write import os.path, but just import os is enough. So, with my built package, why do I have to give the full package path?

Of course I can use from towel_stuff import * to import everything, but was just curious why we don't need to give the full path for standard packages.

2 Answers 2

2

Given the following structure:

towel_stuff
----__init__.py
----towel_utils

When you use import towel_stuff, the only file executed is __init__.py, so if you haven't imported towel_utils in __init__.py, it is not accessible at all.

So in short, when you use import a_module, you are and only are executing the __init__.py file in that module directory. If you want to access the a_module.file, you need to explicitly import it.

When you use import a_file, you are executing that file, as path is just a variable of os, so you can access it like os.path.

So the difference is, path is a variable in os while towel_utils is a submodule in towel_stuff. Or let's say path is an imported module in os which makes it become a variable.

Sign up to request clarification or add additional context in comments.

Comments

1

Normally, for example if we want to use os.path, we don't need to write import os.path, but just import os is enough. So, with my built package, why do I have to give the full package path?

It all depends on how the module is constructed. For example, if in your towel_stuff module you included:

from towel_stuff import towel_utils

Then code that imported only towel_stuff would have access to towel_stuff.towel_utils without additional imports.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.