Emacs plugin to list all methods in a python module - python

Is there a emacs plugin which lists all the methods in the module in a side pane.
I am looking for a plugin which has keyboard shortcuts to show/hide all the methods in python module file currently opened.

I suggest using elpy.
C-c C-o runs elpy-occur-definitions which creates a new buffer with a list of all the class and function signatures.
You can navigate the list using C-n and C-p.
The mode works with next-error-follow minor mode.
So C-c C-f inside the buffer enables jumping to the class or function definition selected.
Here's an example of the contents of that buffer:
8 matches for "^ *\(def\|class\) " in buffer: leveling_utils.py
11:def leveling(episodes_with_potential_associations_by_member):
26:def _apply_leveling(sorted_episodes):
41:def _set_non_chronic_associations(episode):
73:def _apply_sub_to_procedural_association(assoc):
94:def _set_chronic_associations(episode):
102:def _set_associations_for_self(episode):
118:def _set_to_actual(association):
122:def _log_actual_associations(member, leveled_episodes):
By the way, it has many other useful features that to me, make it a necessary addition to python-mode.

For the first question, use M-xspeed-bar, like Alex suggested.
For the second, enable hs-minor-mode, M-xhs-minor-mode, and use C-cC-#C-S-h to hide all methods, and C-cC-#C-S-s to show.

You can look to ECB (it's better to take my fork of it, as it's adapted to fresh Emacs & CEDET) - it can display information about source code fetching it from Semantic (CEDET subpackage) or via imenu (for languages that aren't supported by Semantic).
Speedbar (included into GNU Emacs) can also show a list of top level objects, but doesn't show differences between imports, functions of other top-level stuff

For me, the easiest and most convenient method to quickly lookup methods is the command helm-occur (C-x c M-s o). You start typing the name of the method you want to jump to and suggestions start popping in as you type. Then you hit enter to select the one you want and your cursor jumps right there in the code. Helm-occur wasn't strictly written for this purpose, but works quite well that way.

Speedbar is good, and another nice alternative is helm-imenu. I've bind several keys to access it quicky from different contexts and use it most of the time

Related

IPython 5.0 and key bindings in console

The new release of IPython does not depend any more on readline but uses the pure Python library prompt-toolkit, solving maintenance problems on Apple's and Windows' systems.
A new feature is the ability to edit a multi-line code block, using the cursor keys to move freely in the code block — with this power it comes, at least for me, a problem: because a ret inserts a new line in your code, to pass the whole block to the interpreter you have to use the shortcut alt+ret or possibly the less convenient key sequence esc followed by ret.
I say, this is a problem, because my terminal emulator of choice is the XTerm and, on many Linux distributions, the shortcut alt+ret is not passed to the application but it is directly used by the XTerm in which IPython is running, to toggle the screen-fullness of the said terminal (#ThomasDickey, xterm's mantainer and co-author pointed out that, by default, xterm doesn't care to send to the application the modifier bit on Enter even when one unbinds the Fullscreen action).
For this reason I'd like to modify at least this specific IPython key binding.
I've found instructions (sort of) for the previouos versions, the readline based ones, of IPython that do not apply to the new, 5.0 version.
What I would need are instructions that lead me to find, in IPython's user documentation, the names of the possible actions that I can bind, the names of the shortcuts to bind with the actions and the procedure to follow to configure a new key binding.
Failing to have this type of canonical answer, I may be happy with a recipe to accomplish this specific keybinding, with the condition that the recipe still works in IPython 6.0
You could change xterm's configuration.
xterm is configurable (and documented). In the xterm manual, the Default Key Bindings section shows the default binding for this key:
Alt <Key>Return:fullscreen() \n\
You can suppress that binding in more than one way:
using the omitTranslation resource to suppress the feature
setting the fullscreen resource to never
However, just suppressing it will not make it send something interesting (xterm ignores the modifier for Enter). Setting a translation resource works, e.g., in your $HOME/.Xdefaults file:
*VT100*translations: #override \n\
Alt <Key>Return: string("\033[27;3;13~")
The ctrl+j or ctrl+m keyboard shortcuts are validating the entry.
Modifying keyboard shortcuts in configuration when using prompt_toolkit is not (yet) possible; though it is pretty easy if you install IPython from source. If you look at the file IPython/terminal/shortcuts.py you will see that it contains the various logic; in particular you will find:
# Ctrl+J == Enter, seemingly
registry.add_binding(Keys.ControlJ,
filter=(HasFocus(DEFAULT_BUFFER)
& ~HasSelection()
& insert_mode
))(newline_or_execute_outer(shell))
This bind CtrlJ (enter) to the function newline_or_execute_outer which is responsible for adding new lines; it's define later in the file. In particular if you press enter twice at the end of a block of code, it should execute the block without the need to use any other shortcuts.
Strip the logic that adds new lines:
def execute_outer(shell):
def execute(event):
"""When the user presses return, insert a newline or execute the code."""
b = event.current_buffer
# some logic to also dismiss the completer
b.accept_action.validate_and_handle(event.cli, b)
return execute
Bind it around line 20-something:
registry.add_binding(Keys.ControlE,
filter=(HasFocus(DEFAULT_BUFFER)
& ~HasSelection()
& insert_mode
))(execute_outer(shell))
And enjoy. If you are unhappy with the documentation we welcome help; For example, taking the gist of the answers there and contributing them back. It is a bit hurtful to read harsh comments when we do say in release notes:
New terminal interface
The overhaul of the terminal interface will probably cause a range of minor
issues for existing users. This is inevitable for such a significant
change, and we’ve done our best to minimise these issues. Some changes that
we’re aware of, with suggestions on how to handle them:
IPython no longer uses readline configuration (~/.inputrc). We hope that
the functionality you want (e.g. vi input mode) will be available by
configuring IPython directly (see Terminal IPython options). If something’s
missing, please file an issue.
...
Helping actually improving IPython to have configurable keybinding with actions name is also appreciated, so then you will be able to answer your own question.

VI auto completion Nonesense

I read that CTRL+P is the auto completion short cut in VI, but the recommendation given by the auto completion doesn't make that much sense to me.
Say from the re package there is a method called findall. Eclipse could recommend that method when I do CTRL+Space:
But When I tried the auto completion in VI, it could not find the findall method. the only recommendation seems like a command that I have typed before which has nothing to do with the re module.
Can Anyone give me some hints what is the auto completion story behind the CTRL+P in VI and how could I tune it up so it would be as good as Eclipse's auto completion.
(Every time I doubt the power of VI, the truth is always that it is me who lack the power to discover the beauty of VI)
Thanks!
In vim <C-p> is not the only completion shortcut available. Omni completion defined for python should be called with <C-x><C-o>, then use <C-n>/<C-p> to select variants. There are more completion types, all start with <C-x>, see :h ins-completion.
It is still better to use some third-party plugin (like jedi-vim or klen/python-mode) to get python completion as they are smarter. Note that at least klen/python-mode will not redefine <C-p>. They redefine <C-x><C-o> by setting 'omnifunc' option.
Without any additional modules, vim's autocompletion only searches the current file for occurences of the string you've started typing, regardless of whether it makes sense. If you use the tags file, via ctags or other, you're able to use strings across a variety of files, rather than just the current buffer.

Dangerous Python Keywords?

I am about to get a bunch of python scripts from an untrusted source.
I'd like to be sure that no part of the code can hurt my system, meaning:
(1) the code is not allowed to import ANY MODULE
(2) the code is not allowed to read or write any data, connect to the network etc
(the purpose of each script is to loop through a list, compute some data from input given to it and return the computed value)
before I execute such code, I'd like to have a script 'examine' it and make sure that there's nothing dangerous there that could hurt my system.
I thought of using the following approach: check that the word 'import' is not used (so we are guaranteed that no modules are imported)
yet, it would still be possible for the user (if desired) to write code to read/write files etc (say, using open).
Then here comes the question:
(1) where can I get a 'global' list of python methods (like open)?
(2) Is there some code that I could add to each script that is sent to me (at the top) that would make some 'global' methods invalid for that script (for example, any use of the keyword open would lead to an exception)?
I know that there are some solutions of python sandboxing. but please try to answer this question as I feel this is the more relevant approach for my needs.
EDIT: suppose that I make sure that no import is in the file, and that no possible hurtful methods (such as open, eval, etc) are in it. can I conclude that the file is SAFE? (can you think of any other 'dangerous' ways that built-in methods can be run?)
This point hasn't been made yet, and should be:
You are not going to be able to secure arbitrary Python code.
A VM is the way to go unless you want security issues up the wazoo.
You can still obfuscate import without using eval:
s = '__imp'
s += 'ort__'
f = globals()['__builtins__'].__dict__[s]
** BOOM **
Built-in functions.
Keywords.
Note that you'll need to do things like look for both "file" and "open", as both can open files.
Also, as others have noted, this isn't 100% certain to stop someone determined to insert malacious code.
An approach that should work better than string matching us to use module ast, parse the python code, do your whitelist filtering on the tree (e.g. allow only basic operations), then compile and run the tree.
See this nice example by Andrew Dalke on manipulating ASTs.
built in functions/keywords:
eval
exec
__import__
open
file
input
execfile
print can be dangerous if you have one of those dumb shells that execute code on seeing certain output
stdin
__builtins__
globals() and locals() must be blocked otherwise they can be used to bypass your rules
There's probably tons of others that I didn't think about.
Unfortunately, crap like this is possible...
object().__reduce__()[0].__globals__["__builtins__"]["eval"]("open('/tmp/l0l0l0l0l0l0l','w').write('pwnd')")
So it turns out keywords, import restrictions, and in-scope by default symbols alone are not enough to cover, you need to verify the entire graph...
Use a Virtual Machine instead of running it on a system that you are concerned about.
Without a sandboxed environment, it is impossible to prevent a Python file from doing harm to your system aside from not running it.
It is easy to create a Cryptominer, delete/encrypt/overwrite files, run shell commands, and do general harm to your system.
If you are on Linux, you should be able to use docker to sandbox your code.
For more information, see this GitHub issue: https://github.com/raxod502/python-in-a-box/issues/2.
I did come across this on GitHub, so something like it could be used, but that has a lot of limits.
Another approach would be to create another Python file which parses the original one, removes the bad code, and runs the file. However, that would still be hit-and-miss.

Quickhelp for Python in Emacs autocomplete.el?

I am using Emacs 23.1.1 on GNU/Linux with autocomplete.el 1.3 and Ropemacs 0.6.
In Lisp programming, autocomplete.el shows the documentation (known as 'QuickHelp' in autocomplete.el) of the suggested completions. Python completion with ropemacs works, but does not show quick help for the Python completion. Is it possible to enable it and did somebody make it work?
Ropemacs does the job : Use the function rope-show-doc over the symbol or use the keybinding C-c d. Simple :)
I stopped using all the autocomplete stuff in all my developing environments. They rarely do what I want. Either the lists is too long, or too short, or not sorted well. Therefore I use dabbrev-expand in all my modes global-set-key to tab.
This works even quote well for text. Usually it is enough to get a good expansion from the local buffer where you are in. If I start typing in an empty buffer I open a second one which expand can use to look up its suggestions. This is not language sensitive, not does depend on the object you want to call a method of, but its still a big boost, and you get used to it. Maybe its not, you don't get "quick help" this way.

Jump to Model/View/Controller in emacs

Most rails modes for emacs have this kind of functionality. You are in a controller file over a function "kaboosh" in
"app/controller/bla.rb" and with a keyboard shortcut you switch to "app/views/kaboosh.erb" or to app/models/bla.rb".
A similar functionality exists for .c and .h files using ff-find-other-file.
I checked jump.el and findr.el but all seems a little bit complicated.
I tried searching this for django projects (it would have helped a lot) but no luck.
Anyone knows a simple way (etags?) that it's easy to define the connection between current file/function and target file and then bind it to a keyboard shortcut?
Tags is set up well to jump you to the definition of a function. M-. will take you to the first occurrence of a function definition, C-u M-. will take you to the next (and one after that, and after that...). Perhaps the C-u M-. solves some of your problem.
Regarding associations between files, and wanting a rails like interface, it looks like you could pull out the appropriate chunks of code and customize them for python.
Specifically, you'll need the jump package, make a similar jump schema like the rinari-jump-schema (found in rinari.el). The jump schema uses 'ruby-add-log-current-method (found in ruby-mode.el), and you'd just need to customize that to return the current method name for Python syntax.
It doesn't look like anyone has done this for Python yet, you could be the first. I believe those are the only pieces you'll need.

Categories

Resources