Ipython autocompletion for list or dict of objects - ipython

I would like to have autocompletion in IPython (Jupyter qtconsole or console) for the following case:
I create a class
class MyClass(object):
def __init__(self, a, b):
self.a = a
self.b = b
and put several objects of this class into a list or dict
my_list = []
my_list.append(MyClass(2,3))
my_list.append(MyClass(9,2))
my_list.append(MyClass(8,4))
Now if I do
my_list[0].TAB
autocompletion is not working.
I would like to see a list of my class attributes and methods. Am I missing something or is this just not support in IPython?
Appreciate your help ...

You can execute that in a cell of your Jupyter Notebook:
%config IPCompleter.greedy=True
Which gives (in an ipython/jupyter console, but same in a notebook)
In [10]: my_list[0].<TAB>
my_list[0].a my_list[0].b
To have it permanently, just edit your file ipython_config.py so it looks like this (Commented lines are already present and unmodified, around lines 506-514):
#------------------------------------------------------------------------------
# Completer configuration
#------------------------------------------------------------------------------
# Activate greedy completion
#
# This will enable completion on elements of lists, results of function calls,
# etc., but can be unsafe because the code is actually evaluated on TAB.
c.Completer.greedy = True # <-- uncomment this line and set it to True
If you don't have ipython_config.py in ~/.ipython/profile_default/ you can create one with:
ipython profile create

Related

Elixir macro rewriting module methods and global __using__ macro

With elixir's __using__ macro and with the aid of __on_definition__ I can keep track of all methods in a module. What I would like to do is replace all methods in a module with some other implementation. Now it's fairly trivial to create the new methods I want but I also want to remove the existing methods.
Additionally to this, is there a way to apply a macro to several modules without explicitly adding the use XXX to each module. In otherwords if I have a folder structure:
foo/
bar/
module1.ex
module2.ex
Could I dynamically apply the using macro to everything in ./foo/bar/.
To simplify my problem, imagine that for all methods in all modules in the foo/bar/ folder I want to change there implementation so that they will first run IO.inspect "called before method", aka some kind of before method aop.
def is just a macro from Kernel. So you could exclude it with import Kernel, except: [def: 2] and then create you def. Here is something that almost works, except for the return value.
defmodule Def do
import Kernel, except: [def: 2]
defmacro __using__(_) do
quote do
import Kernel, except: [def: 2]
end
end
defmacro def(call, expr) do
# caller = __CALLER__
# IO.inspect call
# IO.inspect expr
# import Kernel
quote do
Kernel.def unquote(call) do
IO.puts "do something first"
unquote(expr)
end
end
end
end
defmodule Special do
use Def
import Def
def test(one, two) do
IO.puts "one: #{inspect one}, two: #{inspect two}"
end
end
Running in iex
Interactive Elixir (1.4.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Special.test 1, 2
do something first
one: 1, two: 2
[do: :ok]
iex(2)>
I left some print statement at the top of the custom def macro. You can use this to examine the AST of the inputs to the new def macro.
You can find more information in the Kernel source code.
I have not thought of an idea to automatically apply the use to multiple modules at once. I'm come back and update this if I think of anything.

Python Main Function Command Line Argument Long List

I'm trying to make a simple main function for a Caesars Shift cryptography program, however I'm not quite sure how to configure all this command line opt/arg stuff. I want to configure the program to accept command line arguments like so:
./caesars.py -e 13 message to encrypt
with 13 being the amount of shifts and the following lines to be the message to encrypt. I have the functions defined, but I am just not sure how to configure the opt arg stuff to accept the first argument after argv[1] to be the key, then everything after that to get split into a list/long string. Here is what I have so far:
def main():
global decoder
global encoder
if not len(sys.argv[1:]):
usage()
# read the commandline options
try:
opts, args = getopt.getopt(sys.argv[1:],"hd:e:", ¬
["help","decode","encode"])
except getopt.GetoptError as err:
print str(err)
usage()
for o,a in opts:
if o in ("-h","--help"):
usage()
elif o in ("-d","--decode"):
decode = True
elif o in ("-e", "--encode"):
encode = True
else:
assert False,"Unhandled Option"
Thanks in advance.
If you haven't already, you should look into docopt. While I have never used it myself, it's very popular and should be perfect for you.

Why do I get the empty tuple if I type / in iPython?

Open up iPython and type this:
/
Hit enter and wonder about the result:
()
You cannot assign it, my guess it has something to do with the shell functionality.
Edit:
You can assign it with:
p = Out[xx]
But not directly:
p = /
will give:
SyntaxError
It is indeed an empty tuple.
It is a convenience feature for callable objects/names. It's not an empty tuple, but parentheses completion. From iPython's help system (?):
Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
Auto-parentheses
Callable objects (i.e. functions, methods, etc) can be invoked like
this (notice the commas between the arguments)::
In [1]: callable_ob arg1, arg2, arg3
and the input will be translated to this::
callable_ob(arg1, arg2, arg3)
This feature is off by default (in rare cases it can produce
undesirable side-effects), but you can activate it at the command-line
by starting IPython with --autocall 1, set it permanently in your
configuration file, or turn on at runtime with %autocall 1.
You can force auto-parentheses by using '/' as the first character
of a line. For example::
In [1]: /globals # becomes 'globals()'

Individual code formatting for files in Emacs

Is there equivalent plugin like modeline_magic from VIM?
So each file could look like e.g.:
/* vim: set tabstop=8:softtabstop=8:shiftwidth=8:noexpandtab */
int main(int, char *) {}
and indentation would be passed to other clients?
You can add local (file) variables by having a line formatted as
-*- mode: modename; var: value; ... -*-
at the start of your file. Any number of var: value; pairs can appear in the line. If you're finding that you have too many local variables, you can change the style to
# Local Variables:
# mode: python
# comment-column: 0
# End:
Emacs searches for the string "Local Variables", and is smart enough to work out that the prefix and suffix (in this case # and nothing) should be reused for the following lines. This means that if the file is something other than python, you can change the prefix/suffix to match the different comment characters, e.g. /* and */ for ANSI C.
You can read more at the emacs manual.

How to write the output of ipython command in python text file?

I want to capture the output of the following ipython command into a file:
commands and outputs areas follows:
`decoder.get_hyp()`
WARNING: "ngram_search.c", line 1000: </s> not found in last frame, using ++NOISE++ instead
INFO: ngram_search.c(1046): lattice start node <s>.0 end node ++NOISE++.171
INFO: ps_lattice.c(1225): Normalizer P(O) = alpha(++NOISE++:171:185) = -2003082
INFO: ps_lattice.c(1263): Joint P(O,S) = -2036704 P(S|O) = -33622
Out[7]: ('WELCOME TO MY TALK', '000000000', -36704586)
I want to capture only the part "wellcome to my talk" into my file.
Use the IPython magic function store
%store foo >a.txt # Store (overwrite) value of foo to file a.txt
%store foo >>a.txt # Append value of foo to file a.txt
Just do as follow:
%save file_name.py _oh[7]
PS: Some additional useful command:
%save file_name.py _
'_' refers to the previous output.
Or you can:
%save file_name.py _oh[i]
'i' refers to the output history number, you can see output first via:
_oh
The %%capture cell magic saves the stdout/stderr output of running a command, if that's what you need. Here's the usage syntax:
%%capture [--no-stderr] [--no-stdout] [--no-display] [output]
And, here's a usage example:
In [1]: %%capture my_print_output
...: print('test')
...:
In [2]: my_print_output
Out[2]: <IPython.utils.capture.CapturedIO at 0x7f2efa2c12d0>
In [3]: test_output.show()
test
The output object is an instance of IPython.utils.capture.CapturedIO, which has a neat interface for accessing stdout/stderr or combined output.
IPython captures the value (output) of the last command in the variable _ (underscore).
%edit some_variable
will open the value of a variable in your editor.
So, "%edit _", should enable you to edit and save the value of the last command.
See the History section of the IPython docs
And to learn about the possible arguments to the %edit magic function, type the following at the ipython prompt:
%edit?