All Projects → gaogaotiantian → objprint

gaogaotiantian / objprint

Licence: Apache-2.0 License
A library that can print Python objects in human readable format

Programming Languages

python
139335 projects - #7 most used programming language
Makefile
30231 projects

Projects that are alternatives of or similar to objprint

Godbg
Go implementation of the Rust `dbg` macro
Stars: ✭ 172 (+21.99%)
Mutual labels:  debug, print
pydbg
Python implementation of the Rust `dbg` macro
Stars: ✭ 85 (-39.72%)
Mutual labels:  debug, print
alog
Update: use loguru instead. Simple straight logging your Python code
Stars: ✭ 38 (-73.05%)
Mutual labels:  debug, print
Beeprint
make your debug printing more friendly
Stars: ✭ 348 (+146.81%)
Mutual labels:  debug, print
Icecream
🍦 Never use print() to debug again.
Stars: ✭ 5,601 (+3872.34%)
Mutual labels:  debug, print
Icecream Cpp
🍦 Never use cout/printf to debug again
Stars: ✭ 225 (+59.57%)
Mutual labels:  debug, print
consono
The most correct, informative, appealing and configurable variable inspector for JavaScript
Stars: ✭ 17 (-87.94%)
Mutual labels:  debug, print
nativescript-printer
📠 Send an image or the screen contents to a physical printer
Stars: ✭ 33 (-76.6%)
Mutual labels:  print
printer
A fancy logger yet lightweight, and configurable. 🖨
Stars: ✭ 65 (-53.9%)
Mutual labels:  print
hugo-bare-min-theme
A bare minimum theme for Hugo (https://gohugo.io) to help develop and debug Hugo sites -- https://hugo-bare-min.netlify.com/,
Stars: ✭ 71 (-49.65%)
Mutual labels:  debug
mkdocs-print-site-plugin
MkDocs Plugin that adds an additional page that combines all pages, allowing easy exports to PDF and standalone HTML.
Stars: ✭ 38 (-73.05%)
Mutual labels:  print
Unity-File-Debug
Enhanced debug logging for Unity, with JSON/CSV export and HTML viewer.
Stars: ✭ 50 (-64.54%)
Mutual labels:  debug
XDebugger
A very lightweight library (4Kb) to create a development or production debugger with custom errors readable for humans. Includes errors in table format, logger and search methods with dynamic filters.
Stars: ✭ 18 (-87.23%)
Mutual labels:  debug
var-dumper
Helper for dumping variable for debug purposes
Stars: ✭ 13 (-90.78%)
Mutual labels:  debug
kube-debug
一鍵調試kubernetes和docker容器的Web視覺化工具箱。A toolbox for debugging docker container and kubernetes with web UI.
Stars: ✭ 46 (-67.38%)
Mutual labels:  debug
senaite.impress
HTML to PDF Rendering Engine for SENAITE
Stars: ✭ 16 (-88.65%)
Mutual labels:  print
ignition-tinker-tab
An Ignition tab to tinker with your Laravel app
Stars: ✭ 30 (-78.72%)
Mutual labels:  debug
MCUCapture
Utility for plotting array data from MCU RAM
Stars: ✭ 22 (-84.4%)
Mutual labels:  debug
go-getting-started
Develop Go Apps in Kubernetes with Okteto
Stars: ✭ 32 (-77.3%)
Mutual labels:  debug
state inspector
State change & method call logger. A debugging tool for instance variables and method calls.
Stars: ✭ 24 (-82.98%)
Mutual labels:  debug

objprint

build coverage pypi support-version license commit

A library that can print Python objects in human readable format

Install

pip install objprint

Usage

op

Use op() (or objprint()) to print objects.

from objprint import op

class Position:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Player:
    def __init__(self):
        self.name = "Alice"
        self.age = 18
        self.items = ["axe", "armor"]
        self.coins = {"gold": 1, "silver": 33, "bronze": 57}
        self.position = Position(3, 5)

op(Player())
<Player 0x7fe44e1e3070
  .age = 18,
  .coins = {'bronze': 57, 'gold': 1, 'silver': 33},
  .items = ['axe', 'armor'],
  .name = 'Alice',
  .position = <Position
    .x = 3,
    .y = 5
  >
>

You can print multiple objects just like print, except op will print them in separate lines

op([1, 2], {'a': 1})
[1, 2]
{'a': 1}

op will return the same object it prints, so you can do something like this

a = MyObject()
# print the args inline with minumum change
function_using_object(op(a))
# the difference is more significant with complex expressions
# original: function_using_object(a.f() + a.g())
function_using_object(op(a.f() + a.g()))

It works on multiple objects as well, as it returns a tuple, you need to unpack it for functions

a = MyObject()
function_using_object(*op(a.f(), a.g()))

add_objprint

If you want to use print() to print your object, you can also use the class decorator add_objprint to add __str__ method for your class.

from objprint import add_objprint

class Position:
    def __init__(self, x, y):
        self.x = x
        self.y = y

@add_objprint
class Player:
    def __init__(self):
        self.name = "Alice"
        self.age = 18
        self.items = ["axe", "armor"]
        self.coins = {"gold": 1, "silver": 33, "bronze": 57}
        self.position = Position(3, 5)

# This will print the same thing as above
print(Player())

objstr

If you want the str representation of the object, instead of printing it on the screen, you can use objstr function

from objprint import objstr

s = objstr(my_object)

print more

There are some optional information you can print with config.

"Public" Methods

There are no REAL public methods in python, here I simply meant you can print methods that do not start with __ as there will be a lot of default magic methods and you don't want that.

class Player:
    def attack(self, opponent):
        pass

op(Player(), print_methods=True)
<Player 0x7fe44e1e3070
  def attack(opponent)
>

As you can see, it will also print the method signature(without self argument).

Line numbers

You can print execution info, including the function it's in, the file and the line number of the printing line. This is helpful for you to locate where is this object printed.

def f():
    op(Player(), line_number=True)
f()
f (my_script.py:29)
<Player 0x7f30e8cb1ac0
  ...
>

objjson

objprint supports print objects to json to make it easier to serialze an object.

objjson returns a jsonifiable object that can be dumped with json.dumps

from objprint import objjson

json_obj = objjson(Player())

print(json.dumps(json_obj, indent=2))
{
  ".type": "Player",
  "name": "Alice",
  "age": 18,
  "items": [
    "axe",
    "armor"
  ],
  "coins": {
    "gold": 1,
    "silver": 33,
    "bronze": 57
  },
  "position": {
    ".type": "Position",
    "x": 3,
    "y": 5
  }
}

You can use op to print in json format directly with format="json". You can pass in argument for json.dumps

op(Player(), format="json", indent=2)

add_objprint also works with format="json"

@add_objprint(format="json", indent=2)
class Player:
    pass

Enable/Disable the print

You can disable prints from all the op() calls globally with enable config.

from objprint import op

op.disable()
op([1, 2, 3])  # This won't print anything
op.enable()  # This could fix it!

Or you can use it for op() functions individually with some conditions

op(obj, enable=check_do_print())

include/exclude attributes

You can include/exclude attributes using regular expression so objprint will only print out the attributes you are interested in.

op(Player(), include=["name"])
<Player
  .name = 'Alice'
>
op(Player(), exclude=[".*s"])
<Player 0x7fe44e1e3070
  .name = 'Alice',
  .age = 18,
  .position = <Position
    .x = 3,
    .y = 5
  >
>

If you specify both include and exclude, it will do a inclusive check first, then filter out the attributes that match exclusive check.

include and exclude arguments work on objprint, objstr and @add_objprint.

config

objprint formats the output based on some configs

  • config_name(default_value) - this config's explanation
  • enable(True) - whether to print, it's like a switch
  • depth(100) - how deep objprint goes into nested data structures
  • indent(2) - the indentation
  • width(80) - the maximum width a data structure will be presented as a single line
  • elements(-1) - the maximum number of elements that will be displayed, -1 means no restriction
  • color(True) - whether to use colored scheme
  • line_number(False) - whether to print the function (filename:line_number) before printing the object
  • skip_recursion(True) - whether skip printing recursive data, which would cause infinite recursion without depth constraint
  • honor_existing(True) - whether to use the existing user defined __repr__ or __str__ method

You can set the configs globally using config function

from objprint import config
config(indent=4)

Or if you don't want to mess up your name space

from objprint import op
op.config(indent=4)

Or you can do a one time config by passing the arguments into objprint function

from objprint import op

op(var, indent=4)

install

Maybe you don't want to import op in every single file that you want to use. You can use install to make it globally accessible

from objprint import op, install

# Now you can use op() in any file
install()

# This is the same
op.install()

# You can specify a name for objprint()
install("my_print")
my_print(my_object)

Bugs/Requests

Please send bug reports and feature requests through github issue tracker.

License

Copyright Tian Gao, 2020-2021.

Distributed under the terms of the Apache 2.0 license.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].