オブジェクトの現在のすべてのプロパティと値を出力する組み込み関数はありますか?

StackOverflow https://stackoverflow.com/questions/192109

質問

したがって、ここで探しているのは、PHPの print_r 関数のようなものです。これにより、問題のオブジェクトの状態を確認してスクリプトをデバッグできます。

役に立ちましたか?

解決

あなたは本当に2つの異なるものを混ぜています。

dir() vars() または inspect モジュールを使用して、興味のあるものを取得します(例として__builtins__を使用します。代わりに任意のオブジェクトを使用できます)。

>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__

好きなように辞書を印刷します:

>>> print l
['ArithmeticError', 'AssertionError', 'AttributeError',...

または

>>> from pprint import pprint
>>> pprint(l)
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'DeprecationWarning',
...

>>> pprint(d, indent=2)
{ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
  'AssertionError': <type 'exceptions.AssertionError'>,
  'AttributeError': <type 'exceptions.AttributeError'>,
...
  '_': [ 'ArithmeticError',
         'AssertionError',
         'AttributeError',
         'BaseException',
         'DeprecationWarning',
...

プリティプリントは、対話型デバッガーでもコマンドとして使用できます。

(Pdb) pp vars()
{'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,
                  'AssertionError': <type 'exceptions.AssertionError'>,
                  'AttributeError': <type 'exceptions.AttributeError'>,
                  'BaseException': <type 'exceptions.BaseException'>,
                  'BufferError': <type 'exceptions.BufferError'>,
                  ...
                  'zip': <built-in function zip>},
 '__file__': 'pass.py',
 '__name__': '__main__'}

他のヒント

vars()pprint()を混在させる場合:

from pprint import pprint
pprint(vars(your_object))
def dump(obj):
  for attr in dir(obj):
    print("obj.%s = %r" % (attr, getattr(obj, attr)))

作成者の好みに応じて、例外処理、国/特殊文字の印刷、ネストされたオブジェクトへの再帰などのようなものを追加する多くのサードパーティ関数があります。しかし、基本的にはすべてこれに要約されます。

dir が言及されましたが、それは属性の名前を与えるだけです。値も必要な場合は、__ dict__を試してください。

class O:
   def __init__ (self):
      self.value = 3

o = O()

出力は次のとおりです。

>>> o.__dict__

{'value': 3}

オブジェクトの現在の状態を印刷するには、次のようにします。

>>> obj # in an interpreter

または

print repr(obj) # in a script

または

print obj

クラスに対して、__str__または__repr__メソッドを定義します。 Pythonドキュメントから:

  

__repr__(self) repr()組み込み関数および文字列によって呼び出されます   への変換(逆引用符)   <!> quot; official <!> quot;を計算します。ひも   オブジェクトの表現。仮に   可能な場合、これは   有効なPython式   でオブジェクトを再作成するために使用   同じ値(適切な   環境)。これが不可能な場合、   <!> quot; <!> lt; ...の形式の文字列   説明... <!> gt; <!> quot;返される必要があります。   戻り値は文字列でなければなりません   オブジェクト。クラスで repr ()が定義されている場合   __str__()ではなく、__repr__()は   <!> quot; informal <!> quot;ひも   そのインスタンスの表現   クラスが必要です。これは通常   デバッグに使用されるため、重要です   表現が   情報が豊富で明確です。

     

__str__(self)組み込み関数str()および印刷によって呼び出されます   <!> quot; informal <!> quotを計算するステートメント。   オブジェクトの文字列表現。   これは<=>とは異なります   有効なPythonである必要はありません   式:より便利なまたは   簡潔な表現を使用できます   代わりに。戻り値は   文字列オブジェクト。

<!> quot; dir()<!> quot;を使用できます。これを行う関数。

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo
t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder
, 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'
 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault
ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he
version', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_
ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit
, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption
', 'winver']
>>>

もう1つの便利な機能はヘルプです。

>>> help(sys)
Help on built-in module sys:

NAME
    sys

FILE
    (built-in)

MODULE DOCS
    http://www.python.org/doc/current/lib/module-sys.html

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.

    Dynamic objects:

    argv -- command line arguments; argv[0] is the script pathname if known

チェックアウトする価値があるかもしれません-

PerlのData :: Dumperに相当するPythonはありますか?

私の推薦はこれです-

https://gist.github.com/1071857

perlにはData :: Dumperというモジュールがあり、これがオブジェクトデータをperlソースコードに変換することに注意してください(NB:コードをソースに変換しないため、ほとんどの場合、オブジェクトメソッド関数を出力)。これは永続化に使用できますが、一般的な目的はデバッグです。

標準のpython pprintが達成できないものがいくつかあります。特に、オブジェクトのインスタンスを見ると下降を停止し、オブジェクトの内部16進ポインターを提供します(エラー、そのポインターは全体ではありません)ところで使用の)。一言で言えば、Pythonはこの素晴らしいオブジェクト指向のパラダイムに関するものですが、箱から取り出したツールはオブジェクト以外のものを扱うために設計されています。

perl Data :: Dumperを使用すると、行きたい深さを制御したり、循環リンク構造を検出したりできます(これは非常に重要です)。このプロセスは、perlで実現するのが基本的に簡単です。オブジェクトには、その祝福以外の特別な魔法がないためです(普遍的に明確に定義されたプロセス)。

ほとんどの場合、__dict__またはdir()を使用すると、必要な情報を取得できます。詳細が必要な場合は、標準ライブラリに inspect モジュールが含まれています。これにより、印象的な詳細を得ることができます。情報の真のナゲットには次のものがあります。

  • 関数とメソッドのパラメーターの名前
  • クラス階層
  • 関数/クラスオブジェクトの実装のソースコード
  • フレームオブジェクトのローカル変数

<!> quot;オブジェクトの属性値<!> quot;だけを探している場合は、おそらくinspectと<=>で十分です。任意のオブジェクトの現在の状態を掘り下げたい場合(Pythonではほとんどすべてがオブジェクトであることに注意してください)、<=>は検討に値します。

メタプログラミングの例魔法でオブジェクトをダンプ

$ cat dump.py
#!/usr/bin/python
import sys
if len(sys.argv) > 2:
    module, metaklass  = sys.argv[1:3]
    m = __import__(module, globals(), locals(), [metaklass])
    __metaclass__ = getattr(m, metaklass)

class Data:
    def __init__(self):
        self.num = 38
        self.lst = ['a','b','c']
        self.str = 'spam'
    dumps   = lambda self: repr(self)
    __str__ = lambda self: self.dumps()

data = Data()
print data

引数なし:

$ python dump.py
<__main__.Data instance at 0x00A052D8>

Gnosis Utils を使用:

$ python dump.py gnosis.magic MetaXMLPickler
<?xml version="1.0"?>
<!DOCTYPE PyObject SYSTEM "PyObjects.dtd">
<PyObject module="__main__" class="Data" id="11038416">
<attr name="lst" type="list" id="11196136" >
  <item type="string" value="a" />
  <item type="string" value="b" />
  <item type="string" value="c" />
</attr>
<attr name="num" type="numeric" value="38" />
<attr name="str" type="string" value="spam" />
</PyObject>

少し時代遅れですが、まだ機能しています。

これをデバッグに使用していて、すべての再帰ダンプが必要な場合、受け入れられる答えは満足のいくものではありません。クラスにはすでに優れた__str__実装が必要だからです。そうでない場合、これははるかにうまく機能します:

import json
print(json.dumps(YOUR_OBJECT, 
                 default=lambda obj: vars(obj),
                 indent=1))

これにより、すべてのオブジェクトの内容がjsonまたはyamlのインデント形式で再帰的に出力されます。

import jsonpickle # pip install jsonpickle
import json
import yaml # pip install pyyaml

serialized = jsonpickle.encode(obj, max_depth=2) # max_depth is optional
print json.dumps(json.loads(serialized), indent=4)
print yaml.dump(yaml.load(serialized), indent=4)

help(your_object)の使用をお勧めします。

help(dir)

 If called without an argument, return the names in the current scope.
 Else, return an alphabetized list of names comprising (some of) the attributes
 of the given object, and of attributes reachable from it.
 If the object supplies a method named __dir__, it will be used; otherwise
 the default dir() logic is used and returns:
 for a module object: the module's attributes.
 for a class object:  its attributes, and recursively the attributes
 of its bases.
 for any other object: its attributes, its class's attributes, and
 recursively the attributes of its class's base classes.

help(vars)

Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.

一部のログにDEBUG情報を出力する必要がありましたが、pprintが破損するため使用できませんでした。その代わりに、私はこれを行い、実質的に同じことを得ました。

DO = DemoObject()

itemDir = DO.__dict__

for i in itemDir:
    print '{0}  :  {1}'.format(i, itemDir[i])

<!> quot; myObject <!> quot;をダンプするには:

from bson import json_util
import json

print(json.dumps(myObject, default=json_util.default, sort_keys=True, indent=4, separators=(',', ': ')))

vars()とdir()を試しました。私が探していたものの両方が失敗しました。オブジェクトに__dict__がないため、vars()は機能しませんでした(exceptions.TypeError:vars()引数には__dict__属性が必要です)。 dir()は私が探していたものではありませんでした。フィールド名の単なるリストであり、値やオブジェクト構造を提供しません。

json.dumps()はdefault = json_util.defaultがなくてもほとんどのオブジェクトで動作すると思いますが、オブジェクトにdatetimeフィールドがあるため、標準のjsonシリアライザーは失敗しました。 克服する方法<!> quot; datetime.datetime JSONシリアル化不可<!> quot; Pythonで?

from pprint import pprint

def print_r(the_object):
    print ("CLASS: ", the_object.__class__.__name__, " (BASE CLASS: ", the_object.__class__.__bases__,")")
    pprint(vars(the_object))

ppretty

をお試しください
from ppretty import ppretty


class A(object):
    s = 5

    def __init__(self):
        self._p = 8

    @property
    def foo(self):
        return range(10)


print ppretty(A(), show_protected=True, show_static=True, show_properties=True)

出力:

__main__.A(_p = 8, foo = [0, 1, ..., 8, 9], s = 5)

pprint には<!>#8220; prettyプリンターが含まれています< !>#8221;データ構造の見栄えの良い表現を作成します。フォーマッターは、インタープリターが正しく解析できるデータ構造の表現を生成し、人間が読むのも簡単です。出力は、可能であれば1行に保持され、複数の行に分割されるとインデントされます。

単純なものではない理由:

for key,value in obj.__dict__.iteritems():
    print key,value

pprintのみに言及する答えを支持しました。明確にするために、複雑なデータ構造のすべてのを表示したい場合は、次のようにします:

from pprint import pprint
pprint(my_var)

my_var は対象の変数です。 pprint(vars(my_var))を使用したとき、何も得られず、ここでの他の答えが役に立たなかったか、メソッドが不必要に長く見えました。ところで、私の特定のケースでは、私が調べていたコードには辞書の辞書がありました。

いくつかのカスタムクラスでは、役に立たない<someobject.ExampleClass object at 0x7f739267f400>種類の出力になる可能性があることを指摘する価値があります。その場合、__str__メソッドを実装するか、他のソリューションを試してみる必要があります。サードパーティのライブラリなしで、すべてのシナリオで機能するシンプルなものを引き続き探しています。

beeprint を試してください。

これは、オブジェクト変数の出力だけでなく、次のような美しい出力にも役立ちます:

class(NormalClassNewStyle):
  dicts: {
  },
  lists: [],
  static_props: 1,
  tupl: (1, 2)

苦労しているすべての人のために

  • vars()すべての属性を返しません。
  • dir()属性の値を返さない。

次のコードは、obj all 属性をその値とともに印刷します。

for attr in dir(obj):
        try:
            print("obj.{} = {}".format(attr, getattr(obj, attr)))
        except AttributeError:
            print("obj.{} = ?".format(attr))

Flask Debug Toolbarを試すことができます。
https://pypi.python.org/pypi/Flask-DebugToolbar

from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension

app = Flask(__name__)

# the toolbar is only enabled in debug mode:
app.debug = True

# set a 'SECRET_KEY' to enable the Flask session cookies
app.config['SECRET_KEY'] = '<replace with a secret key>'

toolbar = DebugToolbarExtension(app)

Pythonオブジェクトの組み込み型の使用が好きキーまたは

属性がメソッドまたは変数であるかどうかに関係なく:

o.keys()

これらの属性の値の場合:

o.values()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top