Amit
Amit

Reputation: 21

shorten the namespace in python

I want to shorten my namespace from say sandbox.auto.tools to sandbox.tools. How do I achieve that (auto is redundant)? I looked through other messages but didn't really find something similar to what I am looking for. Below is my directory structure.

sandbox\auto\tools\foo.py (contains a function display() as described below)
    def display():
        print "hello"

sandbox\test\bar.py 
    import sandbox.auto.tools as sandbox.tools (Error)

I know I can do the following.

  sandboox\test\bar.py 
    from sandbox.auto.tools import foo as tools
    tools.display()

Any suggestions/pointers ?

Upvotes: 2

Views: 1462

Answers (4)

Amit
Amit

Reputation: 21

One of my colleague pointed out that we could add the following line to sandbox/init.py and it should resolve this specific issue.

path.append('sandbox/auto')

Upvotes: 0

Amit
Amit

Reputation: 21

I finally found a solution with your suggestions/help. However, I am still not satisfied with it.

sandbox/init.py

import auto.tools as tools
__all__ = ['tools']

import sandbox.auto.tools.foo
sandbox.tools.foo = sandbox.auto.tools.foo

sandbox/test/bar.py - this seems to work

import sandbox
print dir(sandbox)
foo = sandbox.tools.foo
foo.display()

However - I cannot say something like this anymore

from sandbox.tools import foo
or
from sandbox.tools import foo as tools2

It looks like I am able to get handle to references but I still don't fully understand the concept of namespaces in python.

Upvotes: 0

wberry
wberry

Reputation: 19367

Allowing the exact syntax you specify (using sandbox.tools instead of sandbox_tools) will require altering the module, either before or after importing it.

The cheap way:

import sandbox.auto.tools
sandbox.tools = sandbox.auto.tools

The permanent way (requires ability to modify the module source):

Create or alter sandbox/__init__.py in the source to say:

import auto.tools as tools
__all__ = ['tools', ...]

Upvotes: 3

jathanism
jathanism

Reputation: 33726

If you really want sandbox.tools to be available, add this to sandbox/__init__.py:

from .auto import tools

This adds tools to the namespace of the sandbox package and you will be able to do this:

from sandbox import tools
tools.dispaly()

Or, what you asked for, which is this:

import sandbox
sandbox.tools.display()

Upvotes: 0

Related Questions