How to show errors in Python code with VSCode - visual-studio-code

I would like to configure VSCode in such a way that I can see red squiggly lines when there is an error in my python code.
My VSCode currently shows me Python syntax errors (e.g. pri nt("hello") will have a red squiggly line), but not the following errors:
class Dog:
attr1 = "mammal"
attr2 = "dog"
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr3)
Rodger = Dog()
print(Rodger.attr1)
Rodger.bark()
In the code above I would like to see a red squiggly line on print("I'm a", self.attr3) since this object doesn't have a self.attr3 attribute, and Rodger.bark() since this object doesn't have a bark method.

I think you might need to add python env path to your vscode.
Press ⌘ + ⇧ + P on the keyboard.
Screenshot
And then choose your python interpreter path.
(VS code will display available python interpreters.)
Then, vscode will detect the attributes itself.
Let me know if you have any questions.

Related

Julia: Vscode extension to send code to the top?

I often find myself adding a new package midway through the code so I need to add using Pkg1 or import Pkg1. But then this code should sit up the top, so I end up scrolling up to the top, type the using code, and then lose track of where I was in the code.
In some python extension, the import statement can be sent to the top for the user.
Is there a vscode extension to do that for julia code?
You can use ctrl+g to travel through lines in VScode.
ctrl+g line 1
ctrl+g line x /*replace x with the line you were*/

VSCode syntax highlight for coffeescript appears to be incomplete

I just started using coffeescript, and I use my preferred editor VSCode in its version 1.45.0 (latest as of today) and its standard theme.
When I write coffeescript code in a file with the file extension .coffee, I get some syntax highlight but it appears to be incomplete.
The code:
name = "Someone"
person = true
age = 19
yell = (number) ->
console.log name, "is now", number
yell(age) if person and name isnt "Scott"
And how it looks like:
screenshot
I find it weird that variables appear differently on second usage, however that might be normal syntax highlight for coffeescript. However, words like "is" or "isnt" aren't recognised.
What I tried:
deactivating all extensions
using https://marketplace.visualstudio.com/items?itemName=yorkxin.coffeescript-support
I searched on Stackoverflow and Google and Github and did not find anything that seemed helpful
Did anyone find a way or does anyone have ideas on how to to write coffeescript in VSCode with more meaningful syntax highlight?

Xcode + swift + Darwin.ncurses = "A_BOLD not found" compilation error. I can't get bright colors

I'm creating a silly utility under XCode 10.2.1, with a swift + ncurses template.
The compilation environment seems amazingly easy to setup:
1.- You import some Darwin.ncurses at the beginning of your main.swift file
2.- You start to invoke the typical ncurses primitives (to create some "color brushes")
3.- You addstrings to the ncurses canvas and your text appears happily rendered.
So far so good, but I need something more than the 8 dark colors my Darwin.ncurses apparently gives. I googled a bit and then I discovered I should emit the "A_BOLD" attribute to my "ncurses attribute manager"™ besides my color brush.
Ok then, that's what I did right before printing my texts, using variations of this instruction:
attron(A_BOLD)
What happened next? Xcode complains (at compilation time) with a "I have no idea what's an A_BOLD".
Apparently all other people with doubts about ncurses complain about their terminals not being able to render bright/bold colors (as their terminals are normally configured wrongly for bright colors). But my terminal IS configured ok.
My problem is at compilation time and I have not the slightest idea about what to do, and what to change to render pure white letters.
All other people seem to be able to compile their ncurses code using the (apparently standard) A_BOLD attribute, why can't I? Is there a different/better Darwin.ncurses alternative which I should use instead?
Thanks.
PS: Here I've added some code snippet so you can see how my code makes Xcode choke:
import Foundation
import Darwin.ncurses
initscr()
start_color()
noecho() // Turn on noecho, though it doesn't matter in this example
curs_set(1) // 0 is invisible, 1 is visible, 2 is very visible
init_pair(1, Int16(COLOR_WHITE), Int16(COLOR_BLUE) )
init_pair(2, Int16(COLOR_WHITE), Int16(COLOR_GREEN) )
move(0, 0)
attron(COLOR_PAIR(1))
addstr("text 1")
attroff(COLOR_PAIR(1))
// nice text appears on screen (with dark dull color palette)
move(2, 0)
attron(COLOR_PAIR(2))
addstr("text 2")
attroff(COLOR_PAIR(2))
// nice text appears below (with dark dull color palette also)
attron(A_BOLD) // <-- THIS line is the one complaining
addstr("text 3")
attroff(A_BOLD) // <-- THIS line is also complaining
attron(COLOR_PAIR(2)|A_BOLD) // <-- THIS line is also complaining
addstr("text 4")
attroff(COLOR_PAIR(2)|A_BOLD) // <-- THIS line is also complaining
refresh()

visual studio code add corresponding import statements for snippets

I tried to create custom snippets for my extension in vscode.
But to use those snippets I also need specific imports statements, I'm trying out to figure out how to add corresponding import statements while a snippet is selected from choices.?
Does vscode provide a way to do this?
If your programming language supports the "Optimize Imports" command, you can take advantage of it to get close to your desired behavior. By default it is set to the shift+opt+O keybinding in vscode.
In JS/TS the "Optimize Imports" command will move an import to the top of a file no matter what line it's written on, as long as it's a syntactically valid import, i.e., not inside a function, etc.
Option 1
You could make your snippet more convenient by ending it on the importable keyword. For example, with a React component snippet that you might need to import, you can use $0 to return to the keyword after supplying the additional content. This would allow you to immediately type cmd+. to "Quick Fix" the import.
{
"AuthorCard": {
"prefix": "ac",
"body": [
"<AuthorCard$0>",
" $1",
"</AuthorCard>"
]
},
}
Option 2
If your function snippet is intended to be inserted into the global scope of the file, then you can include the import in the snippet itself. Then, immediately "Optimize Imports" and it will send the import statement to the top of the file.
For example, the snippet could look like the following.
"blah": {
"prefix": "blah",
"body": [
"import blah from 'blah'",
"export function myBlah() {",
" return blah.doBlah()",
"}"
]
},
Option 3
If you snippet is intended to be used embedded within other scopes within the file, then create a second snippet of the just the import. E.g., for a snippet blah, the snippet iblah could import all the required dependencies. Now, you only need a "quick" way to get to a valid scope for the imports and then back to the place you started, both of which are possible in vscode. I will mention the default keybindings, but, for the record, you can rebind the underlying commands to whatever you'd like.
To get to a valid scope for your import snippet, you have multiple options. The best options is probably cmd+up, which will take you to the top of the file. Other options are shift+cmd+\, which takes you to the closing bracket of a statement, and cmd+enter, which takes you to a new line. From a valid scope you can trigger your import snippet and then "Optimize Imports" with shift+opt+O.
Lastly, to return to your original function, you can "Go Back" in vscode which defaults to ctrl+-, which returns your to your last cursor position.
These options might be less than ideal, especially if you are intending these to be public snippets for an extension package, but, still, they are a collection of convenient tricks that might provide useful (and answer the "spirit" of your question).

Copying variable contents to clipboard while debugging in Visual Studio Code

I'm debugging in Visual Studio Code and I have a JSON object that I would like to copy as text to the clipboard.
Is this possible inside of Visual Studio Code?
I found two ways to do that, both of which are a bit hacky (in my eyes).
Use console.log
I think there will be a limit to the size of the string that this can output, but it was satisfactory for my requirements.
In the debug console, write console.log(JSON.stringify(yourJsonObject))
Copy the resulting output from the debug console. That can be a bit tedious for long strings, but a combination of mouse and keyboard (ctrl-shift-end) worked ok for me.
Use a watch (limited to 10'000 characters)
This method only works up to a limited size of the resulting json string (it looks like 10'000 characters).
Set a breakpoint in a reasonable location where your variable is in scope and start your app.
Go to the debug view, add a watch for a temporary variable, e.g. tmpJson
Get your breakpoint to hit.
In the debug console, write var tmpJson = JSON.stringify(yourJsonObject)
This will now have populated the watched variable tmpJson with the string representation of your json object
In the debug view, right click on the watched variable, click copy.
If the string is too long, it cuts it off with a message like the following:
...,"typeName":"rouParallel","toolAssembly":{"id":"ASKA800201","description":"CeonoglodaloD50R6z5","c... (length: 80365)"
But it would work for smaller objects. Maybe this helps some people.
It would be great to have this properly built-in with vscode.
There is an open issue regarding this: https://github.com/microsoft/vscode-java-debug/issues/624
Workaround :
Go to the VARIABLES panel and right click to show contextual menu on a variable
select Set Value
Ctrl+C
(tested on Java, not JavaScript)
I have an easy workaround to copy anything you want:
In the debug console, write JSON.stringify(yourJsonObject)
Copy the string without the double quotes " around the string
Open a browser, such as Chrome, open the inspecting tool, go on the console and write:
copy(JSON.parse("PASTE_THE_STRING_HERE"));
The object is now copy on your keyboard !
If you are debugging Python:
In the DEBUG CONSOLE type, for example:
import json
from pprint import pprint as pp
pp(json.dumps(outDetailsDict))
OUTPUT IS LIKE
{"": {"stn_ix": 43, "stn_name": "Historic Folsom Station (WB)", "name": "", },
...
The fastest way I found to do that on Visual Studio Code was
Adding a breakpoint where is located the object to copy
Right click on object and choose "Add to Watch"
From Watch sidebar, choose option "Copy Value" and it's all! 🎉
Note: this solution seems to work for longer values but not very long values. This answer suggests a 10,000 char limit and uses JSON.stringify(myvar) instead of just str(). On char limit, see also this comment below.
Tested in python debugger
Add the variable to Watch, but converted to string
str(myvar)
Right-click on the value of the watch, and select Copy Value
Now you should get the full value (but not for very long values. See note above).
(var name blurred out):
If you're in debug mode, you can copy any variable by writing copy() in the debug terminal.
This works with nested objects and also removes truncation and copies the complete value.
Tip: you can right click a variable, and click Copy as Expression and then paste that in the copy-function.
While the question presumably deals with JavaScript (JSON) based technologies, many people have posted Python-related posts in this thread. So I'll post a more specific answer for Python, although the reasoning can be extended with some tweaks to JavaScript-based technologies. 😊
Helper strategies for debugging with VSCode
Copying variable FULL VALUE (not truncated) to clipboard while debugging even for very long values and other additional strategies.
1 APPROACH: Access the "Run and Debug" screen and look for the "WATCH" area and double click inside it. Add something like str(<MY_VAR>) which should be the variable you want to find the value of during the debug process;
2 APPROACH: Access the "DEBUG CONSOLE" tab and in the footer (symbol ">") copy and paste the code below or another one of your choice...
def print_py_obj(py_obj, print_id="print_py_obj"):
"""Prints a Python object with its string, type, dir, dict, etc...
Args:
py_obj (Any): Any Python object;
print_id (Optional[str]): Some identifier.
"""
print(" " + str(print_id) + \
" DEBUG >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
print(" 0 STR >>>>>>>>>>>>>>>>>>>>>>>>")
print(str(py_obj))
print(" 0 <<<<<<<<<<<<<<<<<<<<<<<<")
print(" 1 TYPE >>>>>>>>>>>>>>>>>>>>>>>>")
print(type(py_obj))
print(" 1 <<<<<<<<<<<<<<<<<<<<<<<<")
print(" 2 DIR >>>>>>>>>>>>>>>>>>>>>>>>")
print(str(dir(py_obj)))
print(" 2 <<<<<<<<<<<<<<<<<<<<<<<<")
print(" 3 DICT >>>>>>>>>>>>>>>>>>>>>>>>")
try:
print(vars(py_obj))
except Exception:
pass
print(" 3 <<<<<<<<<<<<<<<<<<<<<<<<")
print(" " + str(print_id) + \
" DEBUG <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
print_py_obj(profit, "<MY_VAR_OPTIONAL_IDENTIFIER>")
NOTE: We may have a 10,000 character limitation for both approaches.
Thanks! 🤗🐧🐍
Yup ! That's very much possible
Select breakpoint near your json variable.Debug.
screnshot . Right click on json body and copy value.That's it.
On the selected breakpoint, go to the Debug Console and print(variable)