Development Tip

Python 프로젝트를 구성하는 방법은 무엇입니까?

yourdevel 2020. 10. 26. 21:25
반응형

Python 프로젝트를 구성하는 방법은 무엇입니까?


저는 Python을 처음 사용하고 미니 프로젝트를 시작하고 있지만 "Python Way"에서 폴더를 구성하는 방법에 대해 약간의 의문이 있습니다.

내가 사용하고 PyDev내 개발 환경에서, 나는 새 프로젝트를 만들 때 폴더가 호출 만들어집니다src

+ src

이제에서 PyDev생성 Pydev Module하고PyDev Package

다음과 같은 방법으로 프로젝트를 구성해야합니다.

+ Indicators
    - Moving_averages.py
    - Stochastics.py
+ Strategies
    - Moving_averages_cross.py
- example.py

모듈 및 패키지 측면에서 어떻게 구성 할 수 있습니까? 모듈과 패키지의 의미는 무엇입니까?

친애하는,


패키지는 기본적으로 그 __init__.py아래 파일이 있는 폴더 이며 일반적으로 모듈이 *.py파일 인 일부 모듈 입니다. 그것은과 관련이있다 import주로. __init__.py지표에 추가 하면 다음을 사용할 수 있습니다.

from Indicators.Stochastics import *

또는

from Indicators import Stochastics

그런데 모듈 / 패키지 이름을 소문자로 유지하는 것이 좋습니다. 기능에는 영향을 미치지 않지만 "pythonic"입니다.


파일 시스템 관점에서 a module는로 끝나는 파일 .py이고 a packagemodules 및 (중첩 된) packages를 다시 포함하는 폴더 입니다. Python은 폴더를 파일 package이 포함 된 것으로 인식 __init__.py합니다.

그런 파일 구조

some/
    __init__.py
    foofoo.py
    thing/
        __init__.py
        barbar.py

를 정의합니다 package some.이 module foofoo패키지 thing에는 다시 모듈이있는 중첩 패키지 barbar있습니다. 그러나 패키지와 모듈을 사용할 때 실제로 다음 두 유형을 구분하지 않습니다.

import some

some.dothis() # dothis is defined in 'some/__init__.py'

import some.foofoo # <- module
import some.thing # <- package

패키지 / 모듈 이름을 선택할 때 PEP8을 따르십시오 (예 : 소문자 이름 사용).


참조 파이썬 패키지 템플릿을

디렉토리 구조

    .
    |-- bin
    |   `-- my_program
    |-- docs
    |   `-- doc.txt
    |-- my_program
    |   |-- data
    |   |   `-- some_data.html
    |   |-- __init__.py
    |   |-- submodule
    |   |   `-- __init__.py
    |   |-- helpers.py
    |-- tests
    |   |-- __init__.py
    |   |-- test_helpers.py
    |-- Makefile
    |-- CHANGES.txt
    |-- LICENSE.txt
    |-- README.md
    |-- requirements-dev.txt
    |-- requirements.txt
    `-- setup.py

고양이 Makefile

    PYTHON=`which python`
    NAME=`python setup.py --name`


    all: check test source deb

    init:
        pip install -r requirements.txt --use-mirrors

    dist: source deb

    source:
        $(PYTHON) setup.py sdist

    deb:
        $(PYTHON) setup.py --command-packages=stdeb.command bdist_deb

    rpm:
        $(PYTHON) setup.py bdist_rpm --post-install=rpm/postinstall --pre-uninstall=rpm/preuninstall

    test:
        unit2 discover -s tests -t .
        python -mpytest weasyprint

    check:
        find . -name \*.py | grep -v "^test_" | xargs pylint --errors-only --reports=n
        # pep8
        # pyntch
        # pyflakes
        # pychecker
        # pymetrics

    clean:
        $(PYTHON) setup.py clean
        rm -rf build/ MANIFEST dist build my_program.egg-info deb_dist
        find . -name '*.pyc' -delete

modern-package-template 라이브러리를 확인하고 싶을 수도 있습니다. 몇 가지 질문을 안내하고 꽤 쉽게 배포 할 수있는 무언가를 얻을 수 있도록 도와주는 프로젝트를위한 정말 멋진 기본 레이아웃을 설정하는 방법을 제공합니다.

http://pypi.python.org/pypi/modern-package-template


프로젝트 구조를 결정하기 전에 프로젝트의 목적이 무엇인지 자문 해 보는 것이 좋습니다. 일회성 분석이 될까요? 조사하고 싶은 장난감 컨셉? 배포하려는 완전한 프로젝트입니까? 프로젝트를 구성하는 데 투입하려는 노력의 양은 다릅니다.

  • 일회성 분석이라면 ipython 노트북 을 사용하고 싶습니다 . 노트북은 생각의 흐름을 캡처하고 나중에 참조 할 수 있도록 코드에 마크 업에 메모를 추가 할 수 있습니다.
  • 조사하고 싶은 장난감 개념이라면 가장 잘 작동하는 간단하고 빠른 접근 방식을 찾습니다. 개념을 신속하게 구현하여 실현 가능한지 확인하고 이에 더 많은 시간을 할애 할 가치가 있는지 확인하고자합니다. 파이썬 철학의 일부는 '완벽 함을 추구하지 마십시오. "충분히 좋다"는 것이 종종 그것뿐입니다. 언제든지 나중에 돌아와 최상의 소프트웨어 엔지니어링 관행을 따르는 방식으로 프로젝트를 구성 할 수 있습니다.
  • 나중에 배포 할 수 있도록 프로젝트를 구조화하고 여러 모듈로 확장되도록하려면 다음 구조를 권장합니다.

    projectname
     ├── MANIFEST.in
     ├── setup.py
     ├── README
     ├── .gitignore
     ├── .git
     ├── projectname_env
     └── projectname
         ├── __init__.py
         ├── subpackageone
         │   ├── __init__.py
         │   ├── second_module.py
         │   ├── tests
         │   │   └── test_second_module.py
         │   └── models
         │       └── model1
         ├── first_module.py   
         └── tests
             └── test_second_module.py
    

The detailed reasons why I like this structure are in my blog post, but the basic gist is that the hierarchically lower level projectname directory contains your actual project. Alongside it are all the tools that help manage (git) and package (setup.py, MANIFEST.in) it.


A package is a directory with a __init__.py in it. The difference from a directory is that you can import it.

There isn't a "Python way" per se, but you'll find that it's a good idea to put all your modules in one package with a name related to the project.

Also, to follow the Python style guide, PEP8, the package and module names should be all lowercase. So, if we assume the project is called "Botond Statistics" your structure would be something like this:

botondstats/
    indicators/
        moving_averages.py
        stochastics.py
    strategies/
        moving_averages_cross.py
    example.py

You would then find the Stochastics class by doing

from botondstats.indicators.stochastics.Stochastics

(There are various ways to keep the structure but make imports shorter, but that's another question).

You can put this structure under src/ if you want to, but it's not necessary. I never do. Instead I have a main directory:

BotondStatistics/
    docs/
    botonstats/ # the above structure
    setup.py    # Distutils/distribute configuration for packaging.

In this directory I also typically have a virtualenv so I actually also have bin/ lib/ et al. Development is typically done by running

./bin/python setup.py tests

As I use the Distrubute test runner to run the tests.

That's how I do it. :-)


Try python_boilerplate_template:

https://pypi.python.org/pypi/python_boilerplate_template


The cookiecutter project by audreyr includes several Python project templates:

The package uses a single ~/.cookiecutterrc file to create custom project templates in Python, Java, JS, and other languages.

For example, a Python template compatible with PyPI:

cookiecutter-pypackage

참고URL : https://stackoverflow.com/questions/5155135/how-to-organize-a-python-project

반응형