Python - 載入自己寫的套件/模組/包/Library/Modules

Import Custom Package/Library/Module In Python

Outline

    Original Post

    Import Custom Package/Library/Module In Python


    Library, also called modules, packages in Python. In fact, it seems there is some difference between these words, but I haven’t dived so deep. I don’t think it really matters either. In short, packages mean collections of bulk code, like famous ones, Pandas, and NumPy.

    Many awesome programmers tend to develop their toolkit. It can be simple, but helpful to your effectiveness. I named my package Arsenal.

    Include Custom Packages In Projects

    I use GitHub to execute version control and have a repository called Arsenal. When I start a new project, I always clone the newest version Arsenal to the project directory, then import in the other Python files. Usually, you will keep optimizing and expanding the toolkit, and some inevitable modifying or reconstructing. This method can prevent version conflicts and not crash your previous projects.

    Copy, Paste And Work

    How to load your custom package in projects after all? Just copy-paste the code below.

    import sys
    
    # Assign project_home as project directory
    project_home = u'/Users/Aron/Documents/Project'
    if project_home not in sys.path:
        sys.path = [project_home] + sys.path
    
    # Import whole module or specific function
    import arsenal
    from arsenal import custom_function

    Remember to note that the code only adds the project path to sys.path temporarily, but it won’t affect system settings. You can restart Kernal to check.



    Related Posts

    Aron

    A data scientist working in a retail company, with experience in web design and marketing. Recently dives into cryptocurrency and quantitative investing.

    facebook telegram
    Content Protection by DMCA.com

    Leave a Reply

    • Required fields are market * .
    • Your email address will not be published.
    • Please ensure your email address is correct, then you will get a notification once a new comment reply.

    Your email address will not be published. Required fields are marked *