PyShell and IPython are showing an extra indentation that is not there

159 views Asked by At

I just started using tmux along with slime, PyShell and IPython and I have ran into the following problem.

I am trying to run the following code:

names = ['a', 'b', 'c']
nc = { name : 0 for name in names}
count = 1
for name in names:
    nc[name] += count
    count += 1
print(nc)

and when I normally run the file in terminal using python3 file.py, it correctly returns {'a': 1, 'b': 2, 'c': 3}.

However, when running this with slime, it is saying that there is an unexpected indent and the error message is showing that the following is being inputted:

names = ['a', 'b', 'c']
nc = { name : 0 for name in names}
count = 1
for name in names:
    nc[name] += count
        count += 1
print

However, this is not what I am inputting. Here is a screen shot to show this. Where is the problem coming from?

2

There are 2 answers

1
Nathan Mills On BEST ANSWER

The error is caused by IPython inserting an indent automatically. To turn off automatic indent, use %autoindent command in IPython. To keep the option off when you restart IPython, add the line

c.TerminalInteractiveShell.autoindent=False

to your ipython_config.py which is located in a profile_profilename folder under the ~/.ipython directory on Linux. The default config would be located at ~/.ipython/profile_default/ipython_config.py. If you don't already have a config file, run

ipython profile create default

to create a default profile or name it something else by replacing default in above command with the desired profile name.

0
cafce25 On

The interactive shell you're using isn't made for use with pasted code. It tries to be helpful and indents lines to where it thinks you want them to be indented

To illustrate I'll mark leading spaces provided by the repl with '.' and spaces you pasted with ';'

for name in names:
....;;;;count += 1
........;;;;nc[name] += count

So the problem is the repl trying to assist you. Try to find out a way to either load python code into your repl or to enable a "paste" mode where it will not try to guess an indentation level for you.