开发者

Shorten Python imports?

I'm working on a Django project. Let's call it myproject. Now my code is littered with myproject.folder.file.function. Is there anyway I can remove the need to prefix all my imports and such with myproject.? What if I want to rename my project later? It kind of annoys me that I need to prefix stuff like that when the very file I'm importing it fr开发者_如何转开发om is inside that same project. Shouldn't be necessary.


from myproject.folder import file (horrible name, btw, trampling over the builtin type file, but that's another rant;-), then use file.function -- if file (gotta hate that module name;-) is still too long for you, add e.g. as fi to the from statement, and use fi.function. If you want to rename myproject to myhorror, you only need to touch the from statements addressing it (you could use relative imports, but those would break 2.5 compatibility and therefore ban you from App Engine for now -- too high a price to pay for minor convenience, for me at least;-).

Edit: if just about every file needs some given supporting module, that's a powerful reason for making sure that supporting module lives in a directory (or zipfile) that's on sys.path (it's probably worth doing even if, say, only 30% of the files need that supporting module!-).


import x as y
import x.y as z
from x import y as z

The "as" allows you to give your own name to an imported module. For example, import os as System would allow you to call the components of the os module like so:

System.path.abspath('bla')

For more information about imports, read: Importing Python Modules


If you don't mind clobbering file:

from myproject.folder import file

If you want to make file something shorter:

import myproject.folder.file as f 

You could create your own import statement if you were feeling really fancy:

head = 'myproject.folder.'
def my_import(name,*args,**kwargs):
   try:
       return __import__(name, *args, **kwargs)
   except ImportError: 
       return __import__(head+name, *args, **kwargs)

file = my_import('file')

You can also be outright evil, and hack the builtin python import statement:

head = 'myproject.folder.'

_import = __import__ # don't clobber __import__ yet

def my_import(name,*args,**kwargs):
   try: 
       return _import(name,*args,**kwargs)
   except ImportError:
       return _import(head+name, *args, **kwargs)

__builtins__.__import__ = my_import # God just killed a maintainer

# elsewhere, after the above abomination has run:
import file # I hope you are happy.

Actually, I'm exaggerating the evil of clobbering built-in functions. It's not that bad. But it is a little bit hairy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜