سؤال

I am creating a Python package with multiple modules. I want to make sure that when I import modules within the package that they are importing only from the package and not something outside the package that has the same name.

Is the correct way of doing this is to use relative imports? Will this interfere when I move my package to a different location on my machine (or gets installed wherever on a customer's machine)?

هل كانت مفيدة؟

المحلول

Modern relative imports (here's a reference) are package-relative and package-specific, so as long as the internal structure of your package does not change you can move the package as a whole around wherever you want.

While Joran Beasley's answer should work as well (though does not seem necessary in those older versions of Python where absolute imports aren't the default, as the old style of importing checked within the package's directory first), I personally don't really like modifying the import path like that when you don't have to, especially if you need to load some of those other packages or modules that your modules or packages now shadow.

A warning, however: these do require that the module in question is loaded as part of a package, or at least have their __name__ set to indicate a location in a package. Relative imports won't work for a module when __name__ == '__main__', so if you're writing a simple/casual script that utilizes another module in the same directory as it (and want to make sure the script will refer to the proper directory, things won't work right if the current working directory is not set to the script's), you could do something like import os, sys; sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) (with thanks to https://stackoverflow.com/a/1432949/138772 for the idea). As noted in S.Lott's answer to the same question, this probably isn't something you'd want to do professionally or as part of a team project, but for something personal where you're just doing some menial task automation or the like it should be fine.

نصائح أخرى

the sys.path tells python where to look for imports

add

import sys
sys.path.insert(0,".")

to the top of your main python script this will ensure local packages are imported BEFORE builtin packages (although tbh I think this happens automagically)

if you really want to import only packages in your folder do

import sys
sys.path = ["."]

however I do not recommend this at all as it will probably break lots of your stuff ...

most IDE's (eclipse/pycharm/etc) provide mechanisms to set up the environment a project uses including its paths

really the best option is not to name packages the same as builtin packages or 3rd party modules that are installed on your system

also the best option is to distribute it via a correctly bundled package, this should more than suffice

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top