2016-11-11 3 views
0

Python 3.5.2で奇妙な動作が発生しました。私はクラスFooを持っていて、一度だけコードを実行したいのですが、すべてのインスタンスに対して一度だけを実行します。このコードはclassステートメントのすぐ下に配置されています。このコードをruningて場合annotationsディレクトリが空でない場合、次のエラーメッセージが表示されPython 3.5.2:ディレクトリが空でない場合は "名前が定義されていません"

import os 

class Foo: 

    path = "annotations/" 
    files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))] 

    def __init__(self, x): 
     # do something 
     1+1 

(空のファイルで十分)

Traceback (most recent call last): 
    File "foo.py", line 3, in <module> 
    class Foo: File "foo.py", line 6, in Foo 
    files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))] File "foo.py", line 6, in <listcomp> 
    files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))] 
NameError: name 'path' is not defined 

annotations/が空である場合は、エラーが発生しません。どうして?この奇妙な動作は、単一行forループを使用している場合にのみ発生します。

私はPython 3.5.2を使用しています。 Python 2.7.12で上記のコードを実行すると、エラーは表示されません。

+0

MacOSのPython 3.5.2では再現できません。とにかく 'class'定義ではなく、関数内の' files'の値を計算することをお勧めします。あなたがするのは醜いです。 Pythonを更新/再インストールしてみてください。 – warvariuc

+0

私はPython 3.5.2を使用します。 Ubuntu 16.04システムで動作します。これは私がクラスに静的なコードを追加する通常の方法のようです。なぜこれは醜いはずですか?誰も満足のいく解決策を提示しないなら、おそらく私はPythonを再インストールしようとします。 – null

+1

リスト内包*のネストされたスコープでは、 'path'という名前は表示されないので、' NameError'を取得します。しかし、最も外側の 'for' iterableソースではなく' if'ステートメントでの使用のみ(list comprehensionの外で計算されるため)と 'if'ステートメントは、テストするイテレータに実際に要素がある場合にのみ使用されます。重複を参照してください。 –

答えて

0

私が理解していれば、まず「注釈」パスがなく、「注釈」パスを作成して動作します。そうであれば、スクリプトは "注釈"パスを読み込もうとしますが、パスは存在しないので意味があります。あなたはこのような何か行うことができます

if os.path.exists('annotations/'): 
    files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))] 

または力は、パスを作る:

if not os.path.exists('annotations/'): 
    os.mkdir('annotations/') 
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))] 
+0

これは問題ではありません。ディレクトリが存在します。上の私の編集を参照してください – null

0

あなたがパス定義され、あなたがNameErrorを得ることができない方法がある場合 - あなたが言及しているものを。 は、それはあなたを与える可能性の実行:

OSError: [Errno 2] No such file or directory: 'annotations/'

をシナリオを処理するにはannotations


をという名前のディレクトリが存在しない場合には - それがない場合、あなたはヒューゴが言及したように(ディレクトリを作成する必要があります):

import os 

class Foo: 

    path = "annotations/" 
    if not os.path.exists('annotations/'): 
     os.mkdir('annotations/') 
    files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))] 

    def __init__(self, x): 
     # do something 
     1+1 


if __name__ == "__main__": 
    obj = Foo(1) 
    print 'hello' 

出力は - 絶対にうまく働いすなわちも注釈ディレクトリを作成しましたectory自体:

[[email protected] so_tmp]$ ls 
[[email protected] so_tmp]$ python ../path_issue.py 
hello 
[[email protected] so_tmp]$ ls 
annotations 
[[email protected] so_tmp]$ 
+0

私はNameErrorを取得します。私はこれがなぜ起こったのかを知りません。これは、ターゲットディレクトリが空でない場合にのみ発生します(上記の編集を参照)。 – null

関連する問題