How to auto wrap the VSCode python intelliSence provided by Pylance? - python

PyLance response:
Not converting to markdown wouldn't be a good idea (as it prevents us from using markdown at all in the tooltips). VS Code's plaintext support is broken until 1.52, but maybe then we could add a toggle to say "use plaintext only".
I'm using VSCode to write python, and using Pylance to provide intelliSence. I wonder if it can provide auto wrapped information in a neat way? The intellisense information currently provided mixed all things in a single line which makes it hard to see.
More specifically, the figure below shows the intellisense without auto wrap. I would like the Args: and the following information shows exactly as the green comment writes (each line is one parameter with its explanation). How can I achieve it?
figure 1: intellisense of a user defined class FDNN without auto wrap
figure 2: intellisense of a pytorch class nn.Linear without auto wrap
EDIT 1:
removing the r before comment doesn't work
EDIT 2:
adding - renders better than plain text, but face with _ escape problem.

The solution is simple: Remove the r in front of your docstring
Edit
I have tried the r with a doc string for a function but I can't reproduce the behavior.
If you format the doc string as a kind of Markdown it will display better only it has problems with _ in variable names.
Underline header lines with - (minus) and the text is rendered reasonable.
class FDNN:
"""
Applies a fused fuzzy .....
Args
----
input_size: size of input vector
memfcn: type of membership functions
memparalist: list of tuples of membership functions
"""
def __init__(self):
pass
For functions the rendering of the doc string after you type the opening ( is different, it is used as literal text in the arguments tooltip.
This might be a reason to create an issue for VSC. The descriptions in the different Providers are interpreted differently and should be possible to mark them as plain text or "Markdown"

Related

How can I change the coloring of parentheses and brackets?

This might be a general vsCode question, but I'm trying to make it work in the Microsoft Python plugin for vsCode.
I tried all the textMate definitions that show as intellisense suggestions when editing the settings file but none worked.
I want to either colorize the parentheses, braces & brackets or any other token in order to make a visual difference between the preceding identifier (function name or collection name) and what goes inside the delimiters (function arguments or collection indices)
function(arg1, arg2)
collection[index]
In Visual Studio Code, you can customize a lot of syntax colors to your individual needs.
Let's say we want to change syntax color of a specific comma - for example the one used to seperate function parameters - you'll need to know what identifier that token has. To find out this just hit ctrl+shift+P and type in Developer: Inspect TM Scopes.
Then click anywhere inside an opened script and select the desired character or keyword you want to know more about. As you can see below the identifier for commas between function parameters in Python is punctuation.separator.parameters.python (btw. there is also a token named punctuation.separator.arguments.python, so you could even use a different color for the commas between arguments):
Now that you have the required identifier for that token, you can add the following to your settings.json:
"editor.tokenColorCustomizations": {
"textMateRules": [
{
"scope": "punctuation.separator.parameters.python",
"settings": {
"foreground": "#ff8800",
"fontStyle": "bold"
}
}
]
}
As you can see you're not only able to change the color, you're also able to change font style if you want and you can place as many scopes within "textMateRules" as you want.
This works for parentheses, brackets and curly brackets as well as for colons, any kind of operators, keywords like class, def, etc.
In this way you can adjust syntax coloring without having to change the whole theme. And of course you can do this with nearly every language available in VSCode.
Note: The code above applies changes only to Python language and will display the selected colors only in Python scripts. For other programming languages you'll first have to inspect the code of the desired language (like described above) to find out the identifiers of the tokens (unfortunately I've not yet found a list of all available tokens to choose from, so, if somebody knows from where or how to get it, feel free to add a comment - thx).

What is the proper level of indent for hanging indent with type hinting in python?

What is the proper syntax for a hanging indent for a method with multiple parameters and type hinting?
Align under first parameter
def get_library_book(self,
book_id: str,
library_id: str
)-> Book:
Indent one level beneath
def get_library_book(
self,
book_id: str,
library_id: str
) -> Book:
PEP8 supports the Indent one level beneath case, but does not specify if Align under first parameter is allowed. It states:
When using a hanging indent the following should be considered; there
should be no arguments on the first line and further indentation
should be used to clearly distinguish itself as a continuation line.
PEP8 has many good ideas in it, but I wouldn't rely on it to decide this kind of question about whitespace. When I studied PEP8's recommendations on whitespace, I found them to be inconsistent and even contradictory.
Instead, I would look at general principles that apply to nearly all programming languages, not just Python.
The column alignment shown in the first example has many disadvantages, and I don't use or allow it in any of my projects.
Some of the disadvantages:
If you change the function name so its length is different, you must realign all of the parameters.
When you do that realignment, your source control diffs are cluttered with unnecessary whitespace changes.
As the code is updated and maintained, it's likely that you'll miss some of the alignment when renaming variables, leading to misaligned code.
You get much longer line lengths.
The alignment doesn't work in a proportional font. (Yes, some developers prefer proportional fonts, and if you avoid column alignment, your code will be equally readable in monospaced or proportional fonts.)
It gets even worse if you use column alignment in more complex cases. Consider this example:
let mut rewrites = try_opt!(subexpr_list.iter()
.rev()
.map(|e| {
rewrite_chain_expr(e,
total_span,
context,
max_width,
indent)
})
.collect::<Option<Vec<_>>>());
This is Rust code from the Servo browser, whose coding style mandates this kind of column alignment. While it isn't Python code, exactly the same principles apply in Python or nearly any language.
It should be apparent in this code sample how the use of column alignment leads to a bad situation. What if you needed to call another function, or had a longer variable name, inside that nested rewrite_chain_expr call? You're just about out of room unless you want very long lines.
Compare the above with either of these versions which use a purely indentation-based style like your second Python example:
let mut rewrites = try_opt!(
subexpr_list
.iter()
.rev()
.map( |e| {
rewrite_chain_expr( e, total_span, context, max_width, indent )
})
.collect::<Option<Vec<_>>>()
);
Or, if the parameters to rewrite_chain_expr were longer or if you just wanted shorter lines:
let mut rewrites = try_opt!(
subexpr_list
.iter()
.rev()
.map( |e| {
rewrite_chain_expr(
e,
total_span,
context,
max_width,
indent
)
})
.collect::<Option<Vec<_>>>()
);
In contrast to the column-aligned style, this pure indentation style has many advantages and no disadvantages at all.
Appart from Terrys answer, take an example from typeshed which is the project on Python's GitHub for annotating the stdlib with stubs.
For example, in importlib.machinery (and in other cases if you look) annotations are done using your first form, for example:
def find_module(cls, fullname: str,
path: Optional[Sequence[importlib.abc._Path]]
) -> Optional[importlib.abc.Loader]:
Read the previous line of PEP 8 more carefully, the part before "or using a hanging indent".
Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent.
This is intended to cover the first "yes' example, and your first example above.
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)

How to let pyflakes ignore some errors?

I am using SublimePythonIDE which is using pyflakes.
There are some errors that I would like it to ignore like:
(E501) line too long
(E101) indentation contains mixed spaces and tabs
What is the easiest way to do that?
Configuring a plugin in Sublime almost always uses the same procedure: Click on Preferences -> Package Settings -> Plugin Name -> Settings-Default to open the (surprise surprise) default settings. This file generally contains all the possible settings for the plugin, usually along with comments explaining what each one does. This file cannot be modified, so to customize any settings you open Preferences -> Package Settings -> Plugin Name -> Settings-User. I usually copy the entire contents of the default settings into the user file, then customize as desired, then save and close.
In the case of this particular plugin, while it does use pyflakes (as advertised), it also makes use of pep8, a style checker that makes use of the very same PEP-8 official Python style guide I mentioned in the comments. This knowledge is useful because pyflakes does not make use of specific error codes, while pep8 does.
So, upon examination of the plugin's settings file, we find a "pep8_ignore" option as well as a "pyflakes_ignore" one. Since the error codes are coming from pep8, we'll use that setting:
"pep8_ignore": [ "E501", // line too long
"E303", // too many blank lines (3)
"E402" // module level import not at top of file
]
Please note that codes E121, E123, E126, E133, E226, E241, E242, and E704 are ignored by default because they are not rules unanimously accepted, and PEP 8 does not enforce them.
Regarding long lines:
Sometimes, long lines are unavoidable. PEP-8's recommendation of 79-character lines is based in ancient history when terminal monitors only had 80 character-wide screens, but it continues to this day for several reasons: it's backwards-compatible with old code, some equipment is still being used with those limitations, it looks good, it makes it easier on wider displays to have multiple files open side-by-side, and it is readable (something that you should always be keeping in mind when coding). If you prefer to have a 90- or 100-character limit, that's fine (if your team/project agrees with it), but use it consistently, and be aware that others may use different values. If you'd like to set pep8 to a larger value than its default of 80, just modify the "pep8_max_line_length" setting.
There are many ways to either decrease the character count of lines to stay within the limit, or split long lines into multiple shorter ones. In the case of your example in the comments:
flag, message = FacebookUserController.AddFBUserToDB(iOSUserId, fburl, fbsecret, code)
you can do a couple of things:
# shorten the module/class name
fbuc = FacebookUserController
# or
import FacebookUserController as fbuc
flag, message = fbuc.AddFBUserToDB(iOSUserId, fburl, fbsecret, code)
# or eliminate it all together
from FacebookUserController import AddFBUserToDB
flag, message = AddFBUserToDB(iOSUserId, fburl, fbsecret, code)
# split the function's arguments onto separate lines
flag, message = FacebookUserController.AddFBUserToDB(iOSUserId,
fburl,
fbsecret,
code)
# There are multiple ways of doing this, just make sure the subsequent
# line(s) are indented. You don't need to escape newlines inside of
# braces, brackets, and parentheses, but you do need to outside of them.
As others suggest, possibly heed the warnings. But in those cases where you can't, you can add # NOQA to the end offending lines. Note the two spaces before the # as that too is a style thing that will be complained about.
And if pyflakes is wrapped in flake8 that allows ignoring by specific errors.
For example in a file in the project put or add to tox.ini:
[flake8]
exclude = .tox,./build
filename = *.py
ignore = E501,E101
This is possibly a duplicate with How do I get Pyflakes to ignore a statement?

More advanced syntax coloring in emacs for Python

I've been using emacs 24 (built from the git version). I've started to create a custom theme, but I've noticed that the theming abilities are rather limited, particularly for Python.
I want to be able to assign different colors to things like
'Single quoted strings' vs. "Double quoted strings"
Highlighting of doctests. So if I have something like
def myfunc(x):
"""
This is the docstring.
>>> # These are the examples
>>> print myfunc(x)
1
"""
return 1
I want the This is the docstring to be colored like the string, but I want the print myfunc() to be colored like Python code (or at least differently). For example, in vim, using whatever plugin I have installed, the doctests are colored brown but the strings are colored blue.
Highlighting docstrings differently than regular strings.
Coloring of string formatting characters (like "%s" or "%(newstyle_formatting)s").
Better treatment of r, u, or b preceding ' or ".
Any suggestions for one or all of these?
I might add more things here if I think of them.
Take a look at the description of the variable font-lock-keywords. It is possible to add rules based on regexp:s, but also based on functions so you can write code to decide what should be colored and in which color.
Also, you can use font-lock-add-keywords to add fontification rules to major modes.

How do you enable block folding for Python comments in TextMate?

In TextMate 1.5.10 r1623, you get little arrows that allow you to fold method blocks:
Unfortunately, if you have a multi-lined Python comment, it doesn't recognize it, so you can't fold it:
def foo():
"""
How do
I fold
these comments?
"""
print "bar"
TextMate has this on their site on how to customize folding: http://manual.macromates.com/en/navigation_overview#customizing_foldings
...but I'm not skilled in regex enough to do anything about it. TextMate uses the Oniguruma regex API, and I'm using the default Python.tmbundle updated to the newest version via GetBundles.
Does anyone have an idea of how to do this? Thanks in advance for your help! :)
Adding the default foldingStartMarker and foldingStopMarker regex values for Python.tmbundle under the Python Language in Bundle Editor:
foldingStartMarker = '^\s*(def|class)\s+([.a-zA-Z0-9_ <]+)\s*(\((.*)\))?\s*:|\{\s*$|\(\s*$|\[\s*$|^\s*"""(?=.)(?!.*""")';
foldingStopMarker = '^\s*$|^\s*\}|^\s*\]|^\s*\)|^\s*"""\s*$';
It appears that multi-line comment folding does work in TextMate, but your must line up your quotes exactly like so:
""" Some sort of multi
line comment, which needs quotes
in just the right places to work. """
That seems to do it:
According to this Textmate Mailing list thread, if you follow it to the end, proper code folding for Python is not supported. Basically, regular expressions as implemented in the foldingStartMarker and foldingStopMarker do not allow for captures, thus the amount of spacing at the beginning of the "end fold" cannot be matched to the "begin fold".
The issue is not finally and officially addressed by Textmate's creator, Allan Odgaard; however since the thread is from 2005, I assume it is a dead issue, and not one that will be supported.

Categories