How to locally develop a python package?

后端 未结 5 579
鱼传尺愫
鱼传尺愫 2021-01-30 18:15

I\'m trying to make changes to an existing python module, and then test it locally. What\'s the best way to do this?

I cloned the github module and made changes, but I\'

5条回答
  •  天命终不由人
    2021-01-30 18:50

    TL; DR

    You can:

    • Overwrite a module/package by creating another one with the same name in the same folder as the script you'll run.
    • Use the develop mode.

    I recommend reading this article that explains pretty well modules and packages.


    Overwriting the module/package

    Description

    You need to create a module or a package (it doesn't make difference) using the same name as the module/package you want and put it in the same folder as the script that it's going to use it.

    This because modules are searched starting from the sys.path variable (where the first element is the script's directory)

    Example

    1. Create a script with the following contents:
    import platform
    
    print(platform.system())
    
    1. Launching it (python your_test_script.py) should return:

    2. Now in the same directory of the previous test script create a file named exactly platform.py with the following contents:

    def system():
        """Just a docstring passing by"""
        return "We have just overwritten default 'platform' module...\nFeel the force!"
    
    1. If you launch the script now, you'll notice the output is different:


    Develop mode

    Description

    Better option if your project is more complicated.

    From the root of your package (where you'd launch the build):

    pip install -e ./ 
    

    Now you're able to edit code and see the changes in real time..


    From The Joy of Packaging:

    It puts a link (actually *.pth files) into the python installation to your code, so that your package is installed, but any changes will immediately take effect.

    This way all your test code, and client code, etc, can all import your package the usual way.

    No sys.path hacking

提交回复
热议问题