Giter Club home page Giter Club logo

icecream's Introduction

icecream

IceCream — Never use print() to debug again

Do you ever use print() or log() to debug your code? Of course you do. IceCream, or ic for short, makes print debugging a little sweeter.

ic() is like print(), but better:

  1. It prints both expressions/variable names and their values.
  2. It's 60% faster to type.
  3. Data structures are pretty printed.
  4. Output is syntax highlighted.
  5. It optionally includes program context: filename, line number, and parent function.

IceCream is well tested, permissively licensed, and supports Python 2, Python 3, PyPy2, and PyPy3.

Inspect Variables

Have you ever printed variables or expressions to debug your program? If you've ever typed something like

print(foo('123'))

or the more thorough

print("foo('123')", foo('123'))

then ic() will put a smile on your face. With arguments, ic() inspects itself and prints both its own arguments and the values of those arguments.

from icecream import ic

def foo(i):
    return i + 333

ic(foo(123))

Prints

ic| foo(123): 456

Similarly,

d = {'key': {1: 'one'}}
ic(d['key'][1])

class klass():
    attr = 'yep'
ic(klass.attr)

Prints

ic| d['key'][1]: 'one'
ic| klass.attr: 'yep'

Just give ic() a variable or expression and you're done. Easy.

Inspect Execution

Have you ever used print() to determine which parts of your program are executed, and in which order they're executed? For example, if you've ever added print statements to debug code like

def foo():
    print(0)
    first()

    if expression:
        print(1)
        second()
    else:
        print(2)
        third()

then ic() helps here, too. Without arguments, ic() inspects itself and prints the calling filename, line number, and parent function.

from icecream import ic

def foo():
    ic()
    first()

    if expression:
        ic()
        second()
    else:
        ic()
        third()

Prints

ic| example.py:4 in foo()
ic| example.py:11 in foo()

Just call ic() and you're done. Simple.

Return Value

ic() returns its argument(s), so ic() can easily be inserted into pre-existing code.

>>> a = 6
>>> def half(i):
>>>     return i / 2
>>> b = half(ic(a))
ic| a: 6
>>> ic(b)
ic| b: 3

Miscellaneous

ic.format(*args) is like ic() but the output is returned as a string instead of written to stderr.

>>> from icecream import ic
>>> s = 'sup'
>>> out = ic.format(s)
>>> print(out)
ic| s: 'sup'

Additionally, ic()'s output can be entirely disabled, and later re-enabled, with ic.disable() and ic.enable() respectively.

from icecream import ic

ic(1)

ic.disable()
ic(2)

ic.enable()
ic(3)

Prints

ic| 1: 1
ic| 3: 3

ic() continues to return its arguments when disabled, of course; no existing code with ic() breaks.

Import Tricks

To make ic() available in every file without needing to be imported in every file, you can install() it. For example, in a root A.py:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from icecream import install
install()

from B import foo
foo()

and then in B.py, which is imported by A.py, just call ic():

# -*- coding: utf-8 -*-

def foo():
    x = 3
    ic(x)

install() adds ic() to the builtins module, which is shared amongst all files imported by the interpreter. Similarly, ic() can later be uninstall()ed, too.

ic() can also be imported in a manner that fails gracefully if IceCream isn't installed, like in production environments (i.e. not development). To that end, this fallback import snippet may prove useful:

try:
    from icecream import ic
except ImportError:  # Graceful fallback if IceCream isn't installed.
    ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a)  # noqa

Configuration

ic.configureOutput(prefix, outputFunction, argToStringFunction, includeContext, contextAbsPath) controls ic()'s output.

prefix, if provided, adopts a custom output prefix. prefix can be a string, like

>>> from icecream import ic
>>> ic.configureOutput(prefix='hello -> ')
>>> ic('world')
hello -> 'world'

or a function.

>>> import time
>>> from icecream import ic
>>>  
>>> def unixTimestamp():
>>>     return '%i |> ' % int(time.time())
>>>
>>> ic.configureOutput(prefix=unixTimestamp)
>>> ic('world')
1519185860 |> 'world': 'world'

prefix's default value is ic| .

outputFunction, if provided, is called once for every ic() call with ic()'s output, as a string, instead of that string being written to stderr (the default).

>>> import logging
>>> from icecream import ic
>>>
>>> def warn(s):
>>>     logging.warning(s)
>>>
>>> ic.configureOutput(outputFunction=warn)
>>> ic('eep')
WARNING:root:ic| 'eep': 'eep'

argToStringFunction, if provided, is called with argument values to be serialized to displayable strings. The default is PrettyPrint's pprint.pformat(), but this can be changed to, for example, handle non-standard datatypes in a custom fashion.

>>> from icecream import ic
>>>
>>> def toString(obj):
>>>    if isinstance(obj, str):
>>>        return '[!string %r with length %i!]' % (obj, len(obj))
>>>    return repr(obj)
>>>
>>> ic.configureOutput(argToStringFunction=toString)
>>> ic(7, 'hello')
ic| 7: 7, 'hello': [!string 'hello' with length 5!]

The default argToStringFunction is icecream.argumentToString, and has methods to register and unregister functions to be dispatched for specific classes using functools.singledispatch. It also has a registry property to view registered functions.

>>> from icecream import ic, argumentToString
>>> import numpy as np
>>>
>>> # Register a function to summarize numpy array
>>> @argumentToString.register(np.ndarray)
>>> def _(obj):
>>>     return f"ndarray, shape={obj.shape}, dtype={obj.dtype}"
>>>
>>> x = np.zeros((1, 2))
>>> ic(x)
ic| x: ndarray, shape=(1, 2), dtype=float64
>>>
>>> # View registered functions
>>> argumentToString.registry
mappingproxy({object: <function icecream.icecream.argumentToString(obj)>,
              numpy.ndarray: <function __main__._(obj)>})
>>>
>>> # Unregister a function and fallback to the default behavior
>>> argumentToString.unregister(np.ndarray)
>>> ic(x)
ic| x: array([[0., 0.]])

includeContext, if provided and True, adds the ic() call's filename, line number, and parent function to ic()'s output.

>>> from icecream import ic
>>> ic.configureOutput(includeContext=True)
>>>
>>> def foo():
>>>   i = 3
>>>   ic(i)
>>> foo()
ic| example.py:12 in foo()- i: 3

includeContext is False by default.

contextAbsPath, if provided and True, outputs absolute filepaths, like /path/to/foo.py, over just filenames, like foo.py, when ic() is called with includeContext == True. This is useful when debugging multiple files that share the same filename(s). Moreover, some editors, like VSCode, turn absolute filepaths into clickable links that open the file where ic() was called.

>>> from icecream import ic
>>> ic.configureOutput(includeContext=True, contextAbsPath=True)
>>>
>>> i = 3
>>>
>>> def foo():
>>>   ic(i)
>>> foo()
ic| /absolute/path/to/example.py:12 in foo()- i: 3
>>>
>>> ic.configureOutput(includeContext=True, contextAbsPath=False)
>>>
>>> def foo():
>>>   ic(i)
>>> foo()
ic| example.py:18 in foo()- i: 3

contextAbsPath is False by default.

Installation

Installing IceCream with pip is easy.

$ pip install icecream

Related Python libraries

ic() uses executing by @alexmojaki to reliably locate ic() calls in Python source. It's magic.

IceCream in Other Languages

Delicious IceCream should be enjoyed in every language.

If you'd like a similar ic() function in your favorite language, please open a pull request! IceCream's goal is to sweeten print debugging with a handy-dandy ic() function in every language.

icecream's People

Contributors

akshay-thakare avatar alexmojaki avatar atusy avatar baopham avatar chang avatar chunqian avatar dominikrafacz avatar ehud-nym avatar gruns avatar helinxu avatar jmerle avatar jtplaarj avatar miggaiowski avatar nodai2hitc avatar ntzm avatar p3r7 avatar palfrey avatar renatogarcia avatar ss18 avatar wlingze avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

icecream's Issues

First release.

Hi there !.
I'd like to debianize this package, do you have any plans on making a release soon? 😃

Abrazo!

Package into a single file

@gruns - I am sure I am in a very tiny minority, but I would be interested in a single-file icecream.py.

My reason for wanting a single file is related to the reason I don't just go ahead and use ycecream.py (since I actually am not particularly interested in the color features). I would love to be able to use icecream with an obscure and esoteric implementation of Python that is stuck at 2.7 and does not have pip or any other easy installers.

Originally posted by @jkyeung in #58 (comment)

Doesn't work with pytest

Under python 3.6, I used ic() regularly in my pytest tests to assist with debugging. Now we have switched our project to python 3.8, and I no longer can. It errors with

ic| Error: Failed to access the underlying source code for analysis. Was ic() invoked in an interpreter (e.g. python -i), a frozen application (e.g. packaged with PyInstaller), or did the underlying source code change during execution?

Is there something I can do to get it working with pytest / python3.8 again?

print() is 68 times faster than ic()

Try the following code to test speed of print() vs ic():

from icecream import ic
from time import time

start = time()
for i in range(1000):
    print("i:", i)
stop = time()
elapsed = stop - start

start = time()
for i in range(1000):
    ic(i)
stop = time()
elapsed2 = stop - start

print(elapsed)
print(elapsed2)
print(f"print() is {elapsed2 / elapsed} times faster than ic()")

I found that print is 68 times faster!
image

How to make it faster? Why is it so slow? Is it because of the coloring?

IC error with class representation broken with unicode

The following code breaks:

# -*- coding: utf-8 -*-
from icecream import ic
from flask_sqlalchemy import SQLAlchemy
import logging
logging.basicConfig(level='INFO')
db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True, nullable=False)

    def __repr__(self):
        return self.name

ic({'a':1}) #WORKS
a=User(name=u'Something ç')
logging.info(a) #WORKS
ic(a) #BREAK

With the following output:

> python .\test_ice.py
ic| {'a':1}: {'a': 1}
INFO:root:Something ç
Traceback (most recent call last):
  File ".\test_ice.py", line 18, in <module>
    ic(a)
  File "D:\Python27\lib\site-packages\icecream\icecream.py", line 310, in __call__
    icWithArgs(callFrame, icNames, args, self._printOut)
  File "D:\Python27\lib\site-packages\icecream\icecream.py", line 293, in icWithArgs
    output = ', '.join('%s: %r' % (arg, value) for arg, value in pairs)
  File "D:\Python27\lib\site-packages\icecream\icecream.py", line 293, in <genexpr>
    output = ', '.join('%s: %r' % (arg, value) for arg, value in pairs)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 10: ordinal not in range(128)

I haven't been really down to the problem but I think it's an issue with the representation returning unicode. You should be able to replicate

Add configuration to turn off ic

It would be good to have an option to turn off all ic calls based on a config option.

Basically when developping you can use ic but in it's too much of a debug tool to be used in production. Thus the production configuration would have all ic turned off (a bit like logging level in production).

Testing whether 'v == ic', should be whether 'v is ic'

When trying to run ic(x) on a numpy.ndarray object, I get an error saying 'the truth value of an array with more than one element is ambiguous', pointing back to the function determinePossibleIcNames. I think a quick fix for the this could be changing the test 'v == ic' to 'v is ic', since the latter tests to see if v and ic point to the same (IceCreamDebugger) object, while the former calls the eq function which is causing the issue.

Icecream highlights all output

When I "print" something with icecream, all output is highlighted as if it were highlighted with text. Unlike normal text highlighting, this cannot be removed when I click/drag on the text. This doesn't happen when I print something normally (using a print statement).

Attached image is a screenshot of what is happening. I have no idea what triggered this.

image_2021-02-19_135135

Allow ic to be used as a decorator

I find that I want to inspect the arguments and return value of a function whenever it's called, but right now I have to go to every line that calls it and add ic() around the call. Moreover, that doesn't even work because it's a Flask function and something messes up.

It would be much better if I could do something like:

@ic
def foo(bar, baz):
    return bar + baz

And get the arguments and return value printed every time the function got called.

Not working with namedtuple

from collections import namedtuple
import icecream as ic

Car = namedtuple('Car', ['color', 'mileage',])

my_car = Car('red', 3812.4)

print(my_car.color)
ic(my_car.mileage)```

Make a command line option for icecream module to find and delete all the `ic` statements in the code

Description

  • This is a great tool for debugging python code. If we could just add a CLI with a remove keyword like so:
ic remove all

this would save devs a lot of time a la Black the linter!

  • Some pseudo code (for the implementation of the CLI functionality):
from os import listdir
from os.path import isfile, join
import re

onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

for file_name in onlyfiles:
    with open(file_name, w):
          re.search("ic").seek(). --> or something like this
          # find and replace logic here

Cannot modify default colours

Hi,
I tried changing the default colours in coloring.py specifically, BASE0 and BASE03 after cloning the repo and running pip install -e ./ in the directory with setup.py as stated here, to install my edited version in developer mode. But it seems this has no effect at all even after many tries and restarting both IDE(Pycharm v2020.3, python 3.8.5) and computer(win10). I don't know if I'm missing something here.

I've been using icecream for a while but the default colours make it difficult for me to make out text in dark mode with Pycharm and I specifically want to change the normal text and whitespace colours since those affect me the most. Thanks.

ValueError when importing icecream with alias

The following exception is thrown when icecream.ic is imported with an alias.

ValueError: min() arg is an empty sequence

How to reproduce

from icecream import ic as foo

foo(1)

throws the above exception instead of the expected output foo| 1: 1

ycecream: a no dependency. Pythonic fork of IceCream

I like the IceCream package very much, but there were several reasons why I made a fork.
This solves also a number of issues raised here.

The ycecream package can be found here: https://github.com/salabim/ycecream and can be installed directly from PyPI.

Here are the main differences:

  • ycecream can't colourize the output (a nice feature of IceCream)
  • ycecream runs only on Python 3.6 and higher. (IceCream runs even on Python 2.7).
  • ycecream uses y as the standard interface, whereas IceCream uses ic. For compatibility, ycecream also supports ic.
  • yceceam has no dependencies. IceCream on the other hand has many (asttoken, colorize, pyglets, ...).
  • ycecream is just one .py file, whereas IceCream consists of a number of .py files. That makes it possible to use ycecream without even (pip) installing it. Just copy ycecream.py to your work directory.
  • ycecream can be used as a decorator of a function or method showing the enter and/or exit event as well as the duration (useful for simple benchmarks)
  • ycecream can output directly to a callable (like IceCream), but also an open file (e.g. sys.stdout) or a file given by the name (strr of Path)
  • ycecream uses a different PEP8 compatible API to customize (rather than IceCream's configureOutput method)
  • ycecream time showing can be controlled independently from context showing
  • ycecream can optionally show a delta (time since start of the program)
  • ycecream does not sort dicts by default. This behaviour can be controlled with the sort_dict parameter. (This is implemented by including the pprint 3.8 source code)
  • ycecream uses pytest for the test scripts rather than IceCream's unittest script.

Tests log on stderr

Hi there!

While running the unittests, I realized that the output goes through stderr. Is there a reason for it?

 ±- python3 -m unittest tests/test_icecream.py > /dev/null 

......................
----------------------------------------------------------------------
Ran 22 tests in 0.071s

OK

I've spent some time trying to understand if its a side effect of the captureStandardStreams method, but couln't find the reason.

This matters because autopkgtest checks that the stderr is null 😞
https://salsa.debian.org/debian/python-icecream/-/jobs/17084

Cannot import install

Hi,

just installed icecream on a sample project and tried to use it according the instructions by importing install and use it as a builtin module. For some reason install isn't there:

ImportError: cannot import name 'install' from 'icecream'

Either it has been removed and the docs on the Github page are old or I missed something.
Regards, Thomas

Stack Traces

Sometimes I would love to see a stack trace as well when calling ic.

irondb

Hello I don't know how to reach you elsewhere, so I created issue here.

As I understand this guys https://www.irondb.io/ have conflict over your naming.

Why the heck github suspended irondb repo?
Why you don't just rename it? I know it's "your name" too, but seriously what's the point?

p.s. I just want to start use it, after you cut lodash :)

Logo license

Does the icecream logo in the README fall under the MIT license aswell? More specifically, can it be used in other language ports of icecream without problems?

Call icecream without having to import it each time.

Hi there,

I like icecream a lot. :) ... However, I often fall back to print() because I'm to lazy to type in from icecream import ic before each call. I guess it would be awesome if one could add icecream to the builtins or globals or something.

I tried adding ic() to the buildins like this:

import builtins

def ic(x=None):
    from icecream import ic as ic_tmp
    if x:
        ic_tmp(x)
    else:
        ic_tmp()


builtins.ic = ic

This allow me to call ic() without having to import it first, but of cause this messes up ic's output...

I was wondering if anyone has got an idea how to make ic global or builtin without breaking it?

IPython magic %time break ic

from snoop import pp kind of works
but from icecream import ic does not work in this context.
image

If you can't see above image, here's the cell in Jupyter Notebook:

%time pp(2+2)
%time ic(3+3)

And here's the output:

01:26:16.74 LOG:
01:26:16.74 .... <argument> = 4
ic| Error: Failed to access the underlying source code for analysis. Was ic() invoked in an interpreter (e.g. python -i), a frozen application (e.g. packaged with PyInstaller), or did the underlying source code change during execution?
Wall time: 0 ns
Wall time: 34.9 ms

Compatibility with ipython "autoreload" extension

Currently, icecream breaks if you try to use it inside a module "reloaded" with the %autoreload ipython extension. For example, with the file tmp.py containing the lines:

# tmp.py
from icecream import ic
a = 1
ic(a)

If I start an ipython session I get the following:

In [1]: %load_ext autoreload
In [2]: %autoreload 2
In [3]: import tmp
ic| a: 1

Then certain changes break icecream. For example changing the file contents to

# tmp.py
from icecream import ic
a = 2
ic(a)

works just fine:

In [4]: import tmp
ic| a: 2

However doing more complicated things, for example adding an import statement, breaks it:

# tmp.py
import os
from icecream import ic
a = 1
ic(a)

results in the following:

In [5]: import tmp
ic| Error: Failed to access the underlying source code for analysis. Was ic() invoked in an inte
rpreter (e.g. python -i), a frozen application (e.g. packaged with PyInstaller), or did the unde
rlying source code change during execution?

I don't have a comprehensive list but, more often than not, icecream seems to fail when I have interactive dependencies or am working with functions/classes.

Would it be possible to fix this?

The display time is wrong

The display time is wrong. It is UTC base time, not the time zone set by the system. How can I solve this problem?

Icecream should return it's args

The ic function should return it's argument. That way, you can slap it in the middle of an expression to debug.

For example, if you had this foo(bar(x)) and you suspected the bar function was misbehaving, you could do foo(ic(bar(x))) and it would print the result of bar.

Fix inline list comprehensions

E.g.

ic([i for i in range(3)])

yields

...
  File "/usr/local/lib/python3.6/dist-packages/icecream/icecream.py", line 522, in __call__
    out = self._format(callFrame, *args)
  File "/usr/local/lib/python3.6/dist-packages/icecream/icecream.py", line 557, in _format
    callFrame, icNames, icMethod, prefix, context, args)
  File "/usr/local/lib/python3.6/dist-packages/icecream/icecream.py", line 578, in _formatArgs
    for arg in extractArgumentsFromCallStr(callStr)]
  File "/usr/local/lib/python3.6/dist-packages/icecream/icecream.py", line 578, in <listcomp>
    for arg in extractArgumentsFromCallStr(callStr)]
  File "/usr/local/lib/python3.6/dist-packages/icecream/icecream.py", line 132, in collapseWhitespaceBetweenTokens
    t for t in tokenize.generate_tokens(StringIO(s).readline)
  File "/usr/local/lib/python3.6/dist-packages/icecream/icecream.py", line 132, in <listcomp>
    t for t in tokenize.generate_tokens(StringIO(s).readline)
  File "/usr/lib/python3.6/tokenize.py", line 595, in _tokenize
    raise TokenError("EOF in multi-line statement", (lnum, 0))
tokenize.TokenError: ('EOF in multi-line statement', (2, 0))

TODO(grun): Test if this is fixed by Alex's executing in #33.

issue when using icecream on Windows PyCharm Debugger "Evaluate tool"

I've installed icecream and it seems to work great but when I try to use the "Evaluate tool" on the PyCharm Debugger
as shown in the picture it's printed this message:

ic| Error: Failed to access the underlying source code for analysis. Was ic() invoked in an interpreter (e.g. python -i), a frozen application (e.g. packaged with PyInstaller), or did the underlying source code change during execution?

which I could not find a solution on the web

tempsnip

Using ic in decorator/wrappers; showing alias function and parameters instead of actual function and passed parameters.

When trying to decorate my functions with ic,

In[0]

from icecream import ic
def my_decorator(func, *args, **kwargs):
    def icecream_wrapper(*args, **kwargs):
        ic(func(*args))
    return icecream_wrapper

@my_decorator
def add_two_numbers(a,b):
    return (a+b)

add_two_numbers(1,2)

Out[0]

ic| func(*args): 3

From the above example, instead of printing ic| add_two_numbers(1,2): 3, it instead uses the aliases in the my_decorator function instead. Probably not an issue, just thought it could be nice to have. Any help or suggestions? Cheers :)

ic | Error when using ic with hydra

Description

Hi Ansgar, when trying to use ic inside a function that uses hydra, a Python library for configuration, I got this error:

ic| Error: Failed to access the underlying source code for analysis. Was ic() invoked in an interpreter (e.g. python -i), a frozen application (e.g. packaged with PyInstaller), or did the underlying source code change during execution?

How to replicate

from icecream import ic 
import hydra

@hydra.main(config_path="../configs", config_name="strategies")
def main(cfg):
    
    ic(2)

if __name__=='__main__':
    main()

I say icecream is not compatible with hydra because when removing the decorator hydra, everything works again.

I wonder if you know what could cause this error? Since hydra is a framework that I use frequently, knowing how to fix this error will be really helpful for me. Thank you!

Message without value

I'd like to print the location with a simple message, but without the value. This can give better context to the location without extraneous output. Example:
ic("Flag check.")
prints
ic| main.py:29 in prepare()- "Flag check.": 'Flag check.'
I'd like a simple way to print
ic| main.py:29 in prepare()- "Flag check."

Using `ic` in Jupyter Notebook outputs extra variable

Thanks in advance for this wonderful package.

This is not really issue but wondering if I can get rid of it.
When I am using ic in Jupyter Notebook it always output the content twice if ic is called at the end of the cell. For example, the code cell

from icecream import ic 

x = 5
ic(x)

outputs

ic| x: 5
5

As another example,

ic(5)
ic(10)

outputs

ic| 5
ic| 10
10

This does not happen if ic is no the end of the cell.

Type, np.ndarray shape

Feature request for having ict print type in addition, and icnp (or just plain ic) ( print shape/dtype if argument is a numpy array

prettyprint dictionaries

Suggestion: I think a nice addition would be to prettyprint dictionaries, either by default or by configuration, since debugging often means staring into dict contents for clues.

This could take up a lot of screen real estate for big/deep dicts, but I would still probably vote to enable it by default.

lineWrapWidth not observed properly

The following code:

from icecream import ic

ic.lineWrapWidth = 100

b = 10 * ['123456']
ic(b)

prints

ic| b: ['123456',
        '123456',
        '123456',
        '123456',
        '123456',
        '123456',
        '123456',
        '123456',
        '123456',
        '123456']

, whereas it all fits on one line, like:

ic| b: ['123456', '123456', '123456', '123456', '123456', '123456', '123456', '123456', '123456', '123456']

The reason for this seems to be that pformat uses a wdth of 80 by default and IceCream doesn't communicate the (reduced) line width to pformat.

pip/github version/code inconsistency

Both pip and git currently have v2.0.0, but only git has install. Very confusing if you follow the docs that say pip install and then realize that there is no install() export (though the github source shows it).

IndentationError: unexpected indent

In my source code I am using icecream and on line 401 of gridtrader.py I make the call ic(deepest_i) and it fails with the following stack trace:

INFO:app:Aborting: Traceback (most recent call last):
  File "/home/schemelab/prg/adsactly-gridtrader/gridtrader/gridtrader.py", line 597, in main
    grid_trader.poll()
  File "/home/schemelab/prg/adsactly-gridtrader/gridtrader/gridtrader.py", line 401, in poll
    ic(deepest_i)
  File "/home/schemelab/prg/adsactly-gridtrader/venv/lib/python3.7/site-packages/icecream/icecream.py", line 471, in __call__
    out = self._format(callFrame, *args)
  File "/home/schemelab/prg/adsactly-gridtrader/venv/lib/python3.7/site-packages/icecream/icecream.py", line 498, in _format
    context = self._formatContext(callFrame, icNames, icMethod)
  File "/home/schemelab/prg/adsactly-gridtrader/venv/lib/python3.7/site-packages/icecream/icecream.py", line 590, in _formatContext
    callFrame, icNames, icMethod)
  File "/home/schemelab/prg/adsactly-gridtrader/venv/lib/python3.7/site-packages/icecream/icecream.py", line 613, in _getContext
    _, lineNumber, _ = getCallSourceLines(callFrame, icNames, icMethod)
  File "/home/schemelab/prg/adsactly-gridtrader/venv/lib/python3.7/site-packages/icecream/icecream.py", line 283, in getCallSourceLines
    node for node in ast.walk(ast.parse(parentBlockSource))
  File "/home/schemelab/install/python37/lib/python3.7/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    def poll(self):
    ^
IndentationError: unexpected indent

Add option to skip show of source code

The problem is when I build the project with PyInstaller in onefile mode the iceream can't find the source code. I understand that I can to use ic.disable() but I want to send the exe file with console enabled for testing purposes.

Could you add an option to disable show of sources or simply don't break the app when they are absent? Thanks.

Traceback (most recent call last): File "app.py", line 79, in <module> File "app.py", line 23, in process File "site-packages\icecream\icecream.py", line 322, in __call__ File "site-packages\icecream\icecream.py", line 346, in _format File "site-packages\icecream\icecream.py", line 435, in _formatContext File "site-packages\icecream\icecream.py", line 453, in _getContext File "site-packages\icecream\icecream.py", line 147, in getCallSourceLines File "inspect.py", line 968, in getsource File "inspect.py", line 955, in getsourcelines File "inspect.py", line 786, in findsource OSError: could not get source code

OSError:could not get source code

Hi,gruns:
I installed icecream win pip.

my code

from icecream import ic

ic(1)

It not work and:

Traceback (most recent call last):
File "", line 1, in
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/icecream/icecream.py", line 322, in call
out = self._format(callFrame, *args)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/icecream/icecream.py", line 346, in _format
context = self._formatContext(callFrame, icNames, icMethod)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/icecream/icecream.py", line 435, in _formatContext
callFrame, icNames, icMethod)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/icecream/icecream.py", line 453, in _getContext
_, lineNumber, _ = getCallSourceLines(icNames, icMethod, callFrame)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/icecream/icecream.py", line 144, in getCallSourceLines
parentBlockSource = ''.join(inspect.findsource(code)[0])
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/inspect.py", line 756, in findsource
raise OSError('could not get source code')
OSError: could not get source code

My environment:

  • MacOS 10.13.3
  • Python3.6.1
  • icecream1.3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.