2016-03-29 7 views
3

これは私のプロジェクトの構造(問題を説明するための単なる一例)である。Pythonの絶対インポート行を短くするには?

. 
├── hello_world 
│   ├── __init__.py 
│   └── some 
│    └── very_nested 
│     └── stuff.py 
└── tests 
    └── test_stuff.py 

py.test用)test_stuff.pyファイル:

from hello_world.some.very_nested.stuff import Magic 
from hello_world.some.very_nested.other_stuff import MoreMagic 

def test_magic_fact_works(): 
    assert Magic().fact(3) == 6 

# ... 

は、インポートラインを作るためにどのようにどのような方法があります短い?実際のプロジェクトでは長すぎます。

たとえば、これはいいだろうが、それは動作しません:)

import hello_world.some.very_nested as vn 
from vn.stuff import Magic 
from vn.other_stuff import MoreMagic 

私は相対的な輸入品を使用することはできませんが(私は仮定)テストがパッケージ内ではありませんbeucase。私はそれらを動かすことができましたが、プロジェクトの構造を変えずに可能ですか?

+3

パッケージスタックの上にある有用な名前を集約するために '__init __。py'ファイルを使用しないのはなぜですか? – jonrsharpe

+0

これは今まで私に迷惑をかけているとは言えません。 PyCharmを使用すると、折り畳まれています。 – wim

+4

'from vn.stuff import Magic'の代わりに' Magic = vn.stuff 'を使うこともできます。同じ効果のための魔法。 – wim

答えて

0

@jonrsharpeは、あなたがDjangoのスタイルであなたのパッケージを集約することができ、言うように:

""" 
Django validation and HTML form handling. 
""" 

from django.core.exceptions import ValidationError # NOQA 
from django.forms.boundfield import * # NOQA 
from django.forms.fields import * # NOQA 
from django.forms.forms import * # NOQA 
from django.forms.formsets import * # NOQA 
from django.forms.models import * # NOQA 
from django.forms.widgets import * # NOQA 

そして、あなたのサブパッケージ内に、例えば:django.forms.widgetsこの追加:どの項目にあなたを指定するには

__all__ = (
    'Media', 'MediaDefiningClass', 'Widget', 'TextInput', 'NumberInput', 
    'EmailInput', 'URLInput', 'PasswordInput', 'HiddenInput', 
    'MultipleHiddenInput', 'FileInput', 'ClearableFileInput', 'Textarea', 
    'DateInput', 'DateTimeInput', 'TimeInput', 'CheckboxInput', 'Select', 
    'NullBooleanSelect', 'SelectMultiple', 'RadioSelect', 
    'CheckboxSelectMultiple', 'MultiWidget', 'SplitDateTimeWidget', 
    'SplitHiddenDateTimeWidget', 'SelectDateWidget', 
) 

import *を使用してインポートする場合、この方法でパッケージを必要なだけ深く整理し、それらを同時にアクセス可能に保つことができます。 from hello_world import Magic

0

:インスタンスのテストであなたのパッケージをインポートするときSO、あなたがこれを取得

hello_world/__

from hello_world.some.very_nested.stuff import * 
from hello_world.some.very_nested.other_stuff import * 

init__.py:

あなたのケースでは、それはようなものになるだろうhello_world/__init__.pyに:

from __future__ import absolute_import 
from .some import * 

hello_world/some/__init__.pyの中へ:

from __future__ import absolute_import 
from .very_nested import * 

hello_world/some/very_nested/__init__.pyの中へ:

from __future__ import absolute_import 
from .stuff import Magic 
from .other_stuff import MoreMagic 

のでhello_world/some/very_nested/stuff.pyが含まれている場合:

class Magic: 
    pass 

そしてhello_world/some/very_nested/other_stuff.pyが含まれています

class OtherMagic: 
    pass 

その後、簡単にインポートできます。 tests/test_stuff.py

関連する問題