steveYeah
steveYeah

Reputation: 351

questions regarding Python namespaces and using import

I'm playing around with Python today and trying out creating my own modules. It seems I don't fully understand Python namespaces and I wonder if anyone could answer my questions about them.

Here is an example of what I've done:

I've created a module named mytest with the following structure:

mytest/
....setup.py
....bin/
....docs/
....mytest/
........__init__.py
........test.py
....tests/

test.py contains one method as follows:

def say_hello():
    print "Hello"

I've installed mytest via distutils. Using 'pip list' I can see the module is installed.

All OK so far, but now I want to use it. I created a test script moduletest.py:

from mytest import test

test.say_hello()

and running this works fine, the 'Hello' message is printed. I was happy with this and started playing around with other methods of importing the module.

The following all seem to work OK:

from mytest.test import say_hello

say_hello()

And:

import mytest.test as test

test.say_hello()

But, the following will not work:

import mytest

test.say_hello()

And:

import mytest

mytest.test.say_hello()

And:

import mytest.test

test.say_hello()

Can anyone explain why you can't import the whole mytest module and then use the parts you want, or why you have to alias test (import mytest.test as test) in order to access it instead of just importing mytest.test (import mytest.test)?

I guess my understanding is a bit off, but some explanation would really help. Thanks!

Upvotes: 2

Views: 72

Answers (2)

Leif Andersen
Leif Andersen

Reputation: 22342

When you do:

import mytest.test

It's adding mytest.test to the global namespace, not test. So what you could do is:

import mytest.test

mytest.test.say_hello()

If you want to just use the line import mytest, what you need to do edit your __init__.py file in you mytest directory to say:

import mytest.test

Then you can do this:

import mytest

mytest.test.say_hello()

Upvotes: 3

OdraEncoded
OdraEncoded

Reputation: 3134

The from..import notation works because you are importing from a package, that doesn't mean the modules are within that package "namespace", it just means they are within the package.

Try doing this in mytest

from . import test

And then do

import mytest
mytest.test.say_hello()

It will work because "test" will be imported into the package namespace.

Upvotes: 1

Related Questions