开发者

Provide a folder out of source where all my external libraries are found

开发者 https://www.devze.com 2023-04-08 00:22 出处:网络
I have the following folder structure lib my_module I have moved all the libraries I need into the lib/ folder.

I have the following folder structure

  • lib
  • my_module

I have moved all the libraries I need into the lib/ folder.

In my module/__init__.py, I think I will do:

import sys
sys.path.append('../lib/')
import my_dependency

Then when I need to use this dependency, I will refer to it as

my_module.my_de开发者_开发技巧pendency

Is this a bad usage of Python import?

NOTE: the dependencies consists of some third-party libraries not available via pip/easy_install and some C++ stuff that I wrote.


sys.path.append('../lib/') assumes that the current working directory is the directory of your script, which may or may not be the case.

A version that doesn't depend on the working directory is:

import sys, os
sys.path.append(os.path.join(os.path.split(os.path.split(os.path.abspath(sys.argv[0]))[0])[0], "lib"))
import my_dependency

The above in plain language takes the full path to the script, chops off the last two components (script directory and script filename) and appends lib.


If the libraries you use are third-party modules—especially popular ones—namespacing them like that is going to get inconsistent pretty fast. You will end up with code that sometimes is referenced as bar and sometimes as foo.bar. Maintaining such a codebase will not be worth whatever gains you expect to get from prefixing them like that.

If you keep third-party code in your own repository, consider replacing it with a requirements.txt file that can be fed to utilities like easy_install and pip. Both these tools support a --user switch that installs to your home directory (not touching system stuff).

pip install -r requirements.txt --user
0

精彩评论

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