VS Code & Python -> Autocomplete missing - python

When writing a search, right after instantiating the actual Search object, auto complete works as expected. After using the query method, I lose the auto-complete.
If i write the code ignoring the fact that intellisense is not suggesting anything, it works ok! (assuming i wrote it correctly)
What am I doing wrong here?
To workaround this, i have a variable commented... if i need auto-complete, i uncomment it, check the auto-complete, and paste it on the appropriate spot...

Related

Python VS code detect incorrect argument name

How can I make VS code detect incorrect argument names?
def test_function(name1, name2, name3):
print(name1)
print(name3)
print(name2)
test_function(name1=1, name2=2, name4=4)
Currently, VS code doesn't flag this as an error. Detecting this would be very useful since argument names change. Otherwise you get an error at run time which is far too late.
VS code is a text editor that one can use to write code in multiple languages but is not a Python interpreter. What you can do is install an extension to do that. For example: Python from Microsoft, has a linter that shows you what problems your code has, including the kind of problem you're describing. Make sure you read the docs to configure it correctly.

QWebEnginePage.print with QPrintPreviewDialog results in empty preview

I have a program that used to use QWebKit to show and print custom generated HTML reports in a dialog and now, I want to convert the whole thing to QWebEngine. Everything works fine so far, only printing doesn't!
Up to now I used QWebView.print() to hand the whole HTML data over to a QPrintPreviewDialog which wasn't a problem at all. Now, from what I understand, I thought I'd have to use QWebEngineView.QWebEnginepage.print(printer object, callback) to achieve the same.
Sadly, everything I tried so far hasn't worked. The preview pane of the QPrintPreviewDialog always stays empty and the result which is given back to the callback after printing is done is always False - although the printer object is still valid the whole time, even in the callback.
I tried out different things, which worked somehow and therefor I think, the QWebEnginePage.print() function is buggy somehow or there is a bug in PyQt, but in fact, I don't and perhaps it is me doing something wrong.
Successful workarounds (which I don't like ;-) ):
Don't use QPrintPreviewDialog, but generate the output via QWebEngineView.QWebEnginePage.printToPDF(filename): worked!
Generate a temporary QTextedit object and print this via QPrintPreviewDialog: also worked, but badly formatted HTML in my case...
Can someone tell me, if I'm assuming something wrong here or if there is a descent example on how to print HTML via QPrintPreviewDialog using QWebEngineView?
QtWebEngine currently doesn't support printing to a print preview, see QTBUG-57982. Printing to a QPrinter directly works though.

Disable on-the-fly PEP8 checks, only check when saving file

I'm using PyCharm Community Edition 4.5.4, and I hate how it notifies me of every little "mistake" I make even when I have full intention of fixing it within 30 seconds.
My style is to kind of write everything at once (instead of finishing one thing before moving to the other), and thus every second word in my code gets highlighted as variable 'x' is not used or Unresolved reference 'x' because I already moved to an other section of my code, intenting to finish the for loop later. If I do something like:
for x in my_list:
pass
And then move to define my_list on top of the file, it will instantly highlight Local variable 'x' is not used. I wish to write my whole code freely, and then after hitting save, I wanna know what mistakes I made.
Is there any way to disable the PEP8 checker, so it would only check when I actually save the file, instead of when I type anything at all?
I have had problems with this issue too.
Unfortunately, there seems to be no documented way of doing what you're requesting. The PyCharm Articles on Code Inspection and Configuring Inspections really don't hint at any such possibility.
Additionally the config file in ~/.PyCharm40/config/inspection/Default.xml isn't what you would call rich in options (note: I have no idea if more options exist, couldn't really find appropriate documentation).
Since pep8.py is apparently ran continuously as a background process in PyCharm, I also checked whether a configuration of these processes was possible. Unfortunately (again), no useful results were found.
To make things worse, there seems to be no relevant plugin available in their plugin repository to allow for further tweaking of the inspection tool.
The other option I tried was by changing the settings in PyCharm and resort to manual calls to pep8. I unselected the inspections for pep8 from Settings | Editor | Inspections | Python tab and then ran the manual inspection by pressing Ctrl + Alt + Shift + I and entering the two pep options. It does not seem to catch the same coding convention errors.
You probably have two options now, one is switching to another IDE as Adam Smith suggested (or noted, actually) and second is trying to maybe get some help on the PyCharm forum.

Code completion not giving recommendations

Say I'm working with the 'requests' Python library.
req = requests.get("http://google.com")
Now after this, if I type req., I'm supposed to get a list of all methods I can access. But for some reason I don't, even if I manually press Ctrl+Space.
If I try this in iPython, I get autocomplete recommendations. Even if I try it via the built in Python console in PyCharm, I get recommendations.
Why's this happening?
As Python is a dynamically typed language, you need to ensure it can work out what type things are, and inspect on the libraries on your system correctly. Try to make sure it's obvious what type the object is in your code.
One good way as of PyCharm 2.7 (back when versions were numbers) is to enable runtime type detection - PyCharm hooks into your program while it runs (while debugging), and checks the types of variables as they are used.
You can enable this by going to settings, going to the "Build, Execution, Deployment" section and then the "Python Debugger" subsection and enabling "Collect run-time types information for code insight".
Obviously it is worth noting that this isn't perfect - if you make changes, this won't be updated til the code is executed, and it can only tell you about values it has seen - other code paths you haven't tried could set other types.
You can also 'tell' PyCharm by using Epydoc or Sphinx style docstrings that contain information about parameter and return value types. PyCharm will use these to improve it's inspections.
Python also gained support for function annotations as of Python 3. These can be used for type hints as per PEP 484. See the typing module for more. This is more formal, so it can also be used for tools like mypy which a type checker that can programmatically check these types for consistency, giving Python a TypeScript-style optional static typing.
Python is a dynamically typed language, which means that the "get" function does not declare its return type. When you're entering code in IPython or in the PyCharm console, the code is actually being executed, and it's possible to inspect the object instance in the running interpreter and to get the list of its methods. When you're entering code in PyCharm or in any other Python IDE, it is not executed, and it's only possible to use static analysis to infer the return type of the method. This is not possible in all cases.
PyCharm has no idea what the dict contains if you fill it dynamically. So you have to hint PyCharm about the keys of dict beforehand. Prodict does exactly this to hint PyCharm, so you get code completion.
First, if you want to be able to access the response object, then you have to get a json response and convert it to dict. That's achieved with .json() method of requests like this:
response = requests.get("https://some.restservice.com/user/1").json()
OK, we loaded it to a dict object, now you can access keys with bracket syntax:
print(response['name'])
Since you ask for auto code completion, you certainly need to hint PyCharm about the keys of dict. If you already know the respone schema, you can use Prodict to hint PyCharm:
class Response(Prodict):
name: str
price: float
response_dict = requests.get("https://some.restservice.com/user/1").json()
response = Response.from_dict(response_dict)
print(response.name)
print(response.price)
In the above code, both name and price attributes are auto-complated.
If you don't know the schema of the response, then you can still use dot-notation to access dict attributes like this:
response_dict = requests.get("https://some.restservice.com/user/1").json()
response = Prodict.from_dict(response_dict)
print(response.name)
But code-completion will not be available since PyCharm can't know what the schema is.
What's more is, Prodict class is derived directly from dict, so you can use it as dict too.
This is the screenshot from Prodict repo that illustrates code completion:
Disclaimer: I am the author of Prodict.
if will just detect methods or variables and... with write some part of it:
File->Setting -> Editor -> General -> Code Completion
in top of opened window , unCheck [ Mach Case ]
It's an old question but probably all the provided answers missed the mark by a margin as wide as Sun's distance to Betelgeuse (none of the answers is accepted and #user1265125 is an active guy with 8 yrs here and more cred than me).
As it happens, I've just had exactly the same problem as OP and the solution was:
A NON-ASCII CHAR SOMEWHERE IN THE PROJECT'S FOLDER PATH
Seriously, PyCharm devs...[doubleFacepalm]
In my case the solution is to reset the settings, everething else wasn`t working for me.
"From the main menu, select File | Manage IDE Settings | Restore Default Settings.Alternatively, press Shift twice and type Restore default settings."
I had a similar problem. Only functions I had already used were suggested and only as plain text and not recognised as methods.
What fixed that for me was deleting the /.idea folder in the project directory. (Afterwards you will have to set your run configurations again)
With the latest version update to 2022.2, even auto-complete stopped working for me. After quite a bit of reading articles, I just found the https://youtrack.jetbrains.com/issue/PY-50489 issue which was the root problem. The old plugins were pending update, after that, the code completion issue was fixed.
So, try and check if you are facing the same problem, if the plugins are up to date in Settings —> Plugins.

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.

Categories

Resources