what are delims used for tab completer - python

I am reading some code about Readline Library I try to type readline.get_completer_delims() it gives me delimiters like ~!##$%^&*()-=+[{]}\|;:'",<>/?
My question is what the meaning of those delimiters for tab complete? can someone explain ?
readline.get_completer_delims()

Per the docs:
Set or get the word delimiters for completion. These determine the start of the word to be considered for completion (the completion scope). These functions access the rl_completer_word_break_characters variable in the underlying library.
These are characters after which the tab completer should consider the start of a "word", and ignore characters on the line prior to that one. For example, if you wanted to implement a tab completer for attributes and methods on Python objects you might add . to this list, so when hitting tab after a . it would indicate that you want completion for whatever comes after the dot.

Related

Matching indentation level according to PEP8/flake8

The question is how to properly break lines according to PEP8 while using TABs.
So here is a related question How to break a line in a function definition in Python according to PEP8. But the issue is that this only works properly when the length of the definition header def dummy( is an integer multiple of the tab length.
def tes(para1=x,
--->--->para2=y)
Otherwise I end up with a new error and flake8 complains about Error E127 or E128 because the its either over- or under-indented like this:
Under-indented E128
def test(para1=x,
--->--->para2=y)
Over-indented
def te(para1=x,
--->--->para2=y)
A solution where flake8 does not complain is to do:
def test(
--->--->para1=x,
--->--->para2=y
--->--->)
However, when I am programming I don't necessarily know in advance how many parameters I'm gonna use in that test() function. So once I hit the line limit I have rearrange quite a bit.
This obviously does apply to all continuations. Does this mean the cleanest solution is to break the line as soon as possible for every line which final length cannot be said by the time of first writing, or is there another solution.
Tab and space shall not be mixed for the solution.
So now I ask myself what is the legis artis to deal with line continuations?
I'm turning my original comment into an official answer.
The PEP-0008 has a section about whether to use Tabs or Spaces, quoted below (with my emphasis):
Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is
already indented with tabs.
Python 3 disallows mixing the use of tabs and spaces for indentation.
Python 2 code indented with a mixture of tabs and spaces should be
converted to using spaces exclusively.
When invoking the Python 2 command line interpreter with the -t
option, it issues warnings about code that illegally mixes tabs and
spaces. When using -tt these warnings become errors. These options are
highly recommended!
You're running into issues with tabs, and you don't say whether you're using Python2 or 3, but I'd suggest you stick to the PEP-0008 guidelines.
You should replace tab chars in the file/module with 4 spaces and use spaces exclusively when indenting.
WARNING: Be very careful if you plan to use shell commands to do this for you, as some commands can be dangerous and mangle intended tab chars within strings (i.e. not only indentation tabs) and can break other things, such as repositories -especially if the command is recursive.
PEP8 is very clear:
Tabs or Spaces?
Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is already indented with tabs.
Python 3 disallows [emphasis added] mixing the use of tabs and spaces for indentation.
Reference: python.org.
So if you're writing new code and want to adhere to standards, just use spaces.

How to make Tab insert a set number of Spaces in Emacs

I want to not use tabs in emacs, I would like to set it so that pressing the tab key inserts a set number of spaces based on the file type. For example, I would like pressing tab to insert 4 spaces when working on a python file. Here is my current .emacs file
(setq-default indent-tabs-mode nil)
(setq tab-width 4)
(setq tab-stop-list (number-sequence 4 200 4))
Currently, whenever I press tab, it only adds any spaces if it is what emacs deems a proper spot. For example, if i opened a python file and pressed tab, nothing would happen. However, if i typed "if:" and then hit tab on the next line, it would add 4 spaces. However, if i pressed tab again, it takes me back to the beginning of the line. I think I would just like to make it so that it adds a set number of spaces, plain and simple(unless someone can give me a good reason for why it's useful to have tab cycle through the line).
The main reason I want this is because I am working on a project where the commenting following a specific format involving the use of indentation based on sets of 4 spaces.
For example:
r"""
Return the value of the q-gamma function.
.. MATH::
qgamma(z,q) = \Gamma_q (z).
"""
So, for the line with "qgamma", I have to start it with 8 spaces, and I would like to be able to od that by pressing tab twice. However, emacs doesn't think this is a proper place to be able to tab twice, so whenever I press tab twice, it takes me back to the beginning of the line.
Thanks!
Edit: checking the major mode variable says that it is on python-mode.
If you're using the built in python.el, you can set indent-line-function to indent-relative instead of python-indent-line-function in python-mode-hook.
(defun jpk/python-mode-hook ()
(setq indent-line-function #'indent-relative))
(add-hook 'python-mode-hook #'jpk/python-mode-hook)
Each major mode has its own indentation function, pointed to by the indent-line-function variable. indent-relative is a very basic, generic indentation function, and is used for fundamental-mode (the most basic major mode).
Python is a bit weird in Emacs in that it has two widely used major modes, the built in python.el and third-party python-mode.el. Use whichever you want, but be aware of which you're using and which people are referring to in articles and SO answers.
M-x customize, search for py-tab-indent, toggle it off and Apply. I believe that's the behavior that you're looking for. Test it out and if so, Apply and Save the customization.
Noting, as #jpkotta pointed out, that the above is for python-mode.el, not the built-in python.el.

Why use an ampersand character (&) in PyQt Strings for GUI elements?

I've read several tutorials for PyQt and they use an ampersand character (&) in Strings which are used to label buttons. For example:
self.submitButton = QPushButton("&Submit")
I searched for some explanation, but one problem is, that common search engines think they're so smart and ignore the & character, which is annoying. When I add quotes around it, it only makes me find less results and none, which explains anything about strange '&' characters.
Is it something very basic and that's why no one is explaining it?
Or is it PyQt specific?
And why would I add an unnecessary character like that?
Doesn't it only clutter the String unnecessarily?
What kind of effect does it have on the handling of that String?
I also tried in the python console:
a = "&abc"
b = "abc"
a == b
which returns false.
Then I tried giving it as an argument to the print function:
print(a)
print(b)
which simple prints:
&abc
abc
So I still don't know what to make of this.
From msdn.microsoft.com: (not related to python itself, but the concept is the same)
Gets or sets a value indicating whether the control interprets an
ampersand character (&) in the control's Text property to be an access
key prefix character.
If the UseMnemonic property is set to true and a mnemonic character (a
character preceded by the ampersand) is defined in the Text property
of the Label, pressing ALT+ the mnemonic character sets the focus to
the control that follows the Label in the tab order. You can use this
property to provide proper keyboard navigation to the controls on your
form.
And from pyqt.sourceforge.net:
A QLabel is often used as a label for an interactive widget. For this
use QLabel provides a useful mechanism for adding an mnemonic (see
QKeySequence) that will set the keyboard focus to the other widget.
E.g.:
QLineEdit* phoneEdit = new QLineEdit(this);
QLabel* phoneLabel = new QLabel("&Phone:", this);
phoneLabel->setBuddy(phoneEdit);

Python PEP: blank line after function definition?

I can't find any PEP reference to this detail. There has to be a blank line after function definition?
Should I do this:
def hello_function():
return 'hello'
or shoud I do this:
def hello_function():
return 'hello'
The same question applies when docstrings are used:
this:
def hello_function():
"""
Important function
"""
return 'hello'
or this
def hello_function():
"""
Important function
"""
return 'hello'
EDIT
This is what the PEP says on the blank lines, as commented by FoxMaSk, but it does not say anything on this detail.
Blank Lines
Separate top-level function and class definitions with two blank
lines.
Method definitions inside a class are separated by a single blank
line.
Extra blank lines may be used (sparingly) to separate groups of
related functions. Blank lines may be omitted between a bunch of
related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
Python accepts the control-L (i.e. ^L) form feed character as
whitespace; Many tools treat these characters as page separators, so
you may use them to separate pages of related sections of your file.
Note, some editors and web-based code viewers may not recognize
control-L as a form feed and will show another glyph in its place.
Read Docstring Conventions.
It says that even if the function is really obvious you have to write a one-line docstring. And it says that:
There's no blank line either before or after the docstring.
So I would code something like
def hello_function():
"""Return 'hello' string."""
return 'hello'
As pointed out by #moliware, the Docstring Conventions state, under One-line Docstrings:
There's no blank line either before or after the docstring.
HOWEVER, it also says (under Multi-line Docstrings):
Insert a blank line after all docstrings (one-line or multi-line) that document a class -- generally speaking, the class's methods are separated from each other by a single blank line, and the docstring needs to be offset from the first method by a blank line.
My interpretation of all this: blank lines should never precede any docstring, and should only follow a docstring when it is for a class.
Projects use different docstring conventions.
For example, the pandas docstring guide explicitly requires you to put triple quotes into a line of their own.
Docstrings must be defined with three double-quotes. No blank lines should be left before or after the docstring. The text starts in the next line after the opening quotes. The closing quotes have their own line (meaning that they are not at the end of the last sentence).
Making a python script simultaneously adhere to pydocstyle and pycodestyle is a challenge. But one thing which greatly helps is that in your docstring write the first line as summary of the function or class within 79 characters including ..This way you adhere to both PEP 257 (as per pydocstyle) of having a period at the end of an unbroken line and 79 characters limit of PEP 8 (as per pycodestyle).
Then after leaving one blank line (for that using new line shortcut of your coditor is better than manually pressing enter) you can write whatever you want and at that time focusing only on pycodestyle which is slightly easier than pydocstyle and the main reason is that our understanding of line and indentation is quite different than what system understands due to indentation settings, tab settings, line settings in the various code editors we use.So in this way you will have TODO from pycodestyle which you understand and can rectify instead of banging your head against the wall on pydocstyle TODOs.

Reverse a word in Vim

How can I reverse a word in Vim? Preferably with a regex or normal-mode commands, but other methods are welcome too:
word => drow
Thanks for your help!
PS: I'm in windows XP
Python is built in supported in my vim, but not Perl.
Here is another (pythonic) solution based on how this works:
:echo join(reverse(split('hello', '.\zs')), '')
olleh
If you want to replace all words in the buffer,
:%s/\(\<.\{-}\>\)/\=join(reverse(split(submatch(1), '.\zs')), '')/g
This works by first creating a list of characters in the word, which is reversed and joined back to form the word. The substitute command finds each word and then passes the word to the expressions and uses the result as replacement.
This Tip might help: http://vim.wikia.com/wiki/Reverse_letters
It says:
Simply enable visual mode (v), highlight the characters you want inverted, and hit \is. For a single word you can use vw (or viw): viw\is
vnoremap <silent> <Leader>is :<C-U>let old_reg_a=#a<CR>
\:let old_reg=#"<CR>
\gv"ay
\:let #a=substitute(#a, '.\(.*\)\#=',
\ '\=#a[strlen(submatch(1))]', 'g')<CR>
\gvc<C-R>a<Esc>
\:let #a=old_reg_a<CR>
\:let #"=old_reg<CR>
There are more solutions in the comments.
Assuming you've got perl support built in to vim, you can do this:
command! ReverseWord call ReverseWord()
function! ReverseWord()
perl << EOF
$curword = VIM::Eval('expand("<cword>")');
$reversed = reverse($curword);
VIM::Msg("$curword => $reversed");
VIM::DoCommand("norm lbcw$reversed");
EOF
endfun
And potentially bind that to a keystroke like so:
nmap ,r :ReverseWord<CR>
I don't have Python supported on my VIM, but it looks like it would be pretty simple to do it with Python. This article seems like a good explanation of how to use Python in VIM and I'm guessing you'd do something like this:
:python 'word'[::-1]
The article indicates that the result will appear in the status bar, which would be non-optimal if you were trying to replace the string in a document, but if you just want to check that your girlfriend is properly reversing strings in her head, this should be fine.
If you have rev installed (e.g. via MSys or Cygwin) then it's really not this difficult.
Select what you want to reverse and filter (%! <cmd>) it:
:%! rev
This pipes your selection to your shell while passing it a command.
if your version of VIM supports it you can do vw\is or viw\is (put your cursor at the first letter of the word before typing the command)... but I have had a lot of compatibility issues with that. Not sure what has to be compiled in or turned on but this only works sometimes.
EDIT:
\is is:
:<C-U>let old_reg_a=#a<CR>
\ :let old_reg=#"<CR>
\ gv"ay :let #a=substitute(#a, '.\(.*\)\#=', '\=#a[strlen(submatch(1))]', 'g')<CR>
\ gvc<C-R>a<Esc> :let #a=old_reg_a<CR>
\ :let #"=old_reg<CR>
Didn't remember where it came from but a google search come this article on vim.wikia.com. Which shows the same thing so I guess that's it.
Well you could use python itself to reverse the line through the filter command. Say the text you had written was:
Python
You could reverse it by issuing.
:1 ! python -c "print raw_input()[::-1]"
And your text will be replaced to become:
nohtyP
The "1" in the command tells vi to send line 1 to the python statement which we are executing: "print raw_input()[::-1]". So if you wanted some other line reversed, you would send that line number as argument. The python statement then reverses the line of input.
There is a tricky way to do this if you have Vim compiled with +rightleft. You set 'allowrevins' which let you hit Ctrl+_ in insert mode to start Reverse Insert mode. It was originally made for inserting bidirectional scripts.
Type your desired word in Insert mode, or move your cursor to the end of an already typed word. Hit Ctrl+_ and then pick a completion (i_Ctrl-x) method which is the most likely not to return any results for your word. Ysing Ctrl+e to cancel in-place completion does not seem to work in this case.
I.e. for an unsyntactic text file you can hit in insert mode Ctrl+x Ctrl+d which is guaranteed to fail to find any macro/function names in the current file (See :h i_CTRL-X_CTRL-D and:h complete for more information).
And voila! Completion lookup in reverse mode makes the looked up word reverse. Notice that the cursor will move to the beginning of that word (it's reversed direction of writing, remember?)
You should then hit Ctrl+_ again to get back to regular insert mode and keyboard layout and go on with editing.
Tip: You can set 'complete' exclusively (for the buffer, at least) to a completion option that is guaranteed to return no result. Just go over the options in :h 'complete'. This will make the easy i_Ctrl-N / i_Ctrl-P bindings available for a handy word reversal session. You can ofcourse further automate this with a macro, a function or a binding
Note: Setting/resetting 'paste' and 'compatible' can set/reset 'allowrevins'. See :h allowrevins.
If you have some time on your hands, you can bubble your way there by iteratively transposing characters (xp)...
I realize I'm a little late to the game, but I thought I'd just add what I think is the simplest method.
It's two things:
Vim's expression register
pyeval (py3eval on recent vim releases) function
So to reverse a word you would do the following:
"ayiw yank word into register a
<C-r>=py3eval('"".join(reversed(str(' . #a ')))') use vim's = (expression) register to call the py3eval function which evaluates python code (duh) and returns the result, which is then fed via the expression register into our document.
For more info on the expression register see https://www.brianstorti.com/vim-registers/#the-expression-and-the-search-registers
you can use revins mode in order to do it:
at the beginning type :set revins. from now on every letter you type will be inserted in a reverse order, until you type :set norevins to turn off. i.e, while revins is set, typing word will output drow.
in order to change an existing word after revins mode is set, and the cursor on beginning of the word, type:
dwi<C-r>"<ESC>
explanation:
dw deleted a word.
i to enter insert mode
<C-r>" to paste the last deleted or yaked text in insert mode, <ESC> to exit insert mode.
remember to :set norevins at the end!

Categories