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 from 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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With