Find where Python function is called in PyCharm - python

Is there a way for PyCharm to show where a given Python function is called from?
I currently rely on simply searching for the function name across the project and this often works fine, but if a function name is vague there are a lot of incorrect hits. I'm wondering if I'm missing a feature somewhere, e.g. perhaps the search results could be further narrowed down to only show where modules import the module I'm searching from?

In PyCharm you can select a function and press Alt+Shift+F7 to run a usage search. It's also available under "Edit → Find → Find Usages". It looks like it's more intelligent than a text search.
Using static analysis to find where a function is called from is difficult in general in Python because it uses dynamic binding and has a lot of introspection so it's very easy to get false positives miss usages. In the case of module-level functions I think a good solution is to always use module.function to call the function and never do a from module import function. That way you can do a text search for 'module.function'. Python style guides generally recommend that you import functions etc. in this way so I think this is generally accepted good practice.
Finding method calls is of course much harder. One of the things I like about developing in Java and C# is being able to find all usages of a method by static analysis.

Press the Ctrl key and simultaneously hover your mouse over the function header.The function name should get highlighted.Click on the function name to get a list of all instances where the function is called.
If you press the Ctrl key and simultaneously hover your mouse over a function call, then the function name will be highlighted and clicking on it will take you to the function definition.

Related

how to find all properties and methods of specific object in dart?

in python, there is a built-in function called dir which displays all properties and methods of the specified object so is there a function like that in Dart if it's what is called?
and also in python, there is another function called type which displays the type of the argument you give so is there a function like that in Dart also?
Dart does not have this kind of feature in runtime unless you are running your code with the Dart VM, in which case you can use dart:mirrors: https://api.dart.dev/stable/2.13.4/dart-mirrors/dart-mirrors-library.html
One reason for this restriction is that Dart are a compiled language, so when compiled to native or JavaScript, the compiler identifies what code are used and only takes what is needed for your program to be executed. It also makes optimizations based on how the code are being used. Both kind of optimizations is rather difficult if you are allowing every method to be accessed.
The Dart VM can do this since it does has access to all the code when running the program.
There are some ongoing discussion about adding meta programming to Dart which might be the solution for most cases where dart:mirrors are used today:
https://github.com/dart-lang/language/issues/1518
https://github.com/dart-lang/language/issues/1565
An alternative solution is use some kind of builder which makes static analysis of your code and compiles some classes based on that which you are then includes in your project. E.g. a class which contains the name and type of all members of the classes you need that information from.

Function arguments suggestion/autocomplete in VSCode for Python

In RStudio, function variables, parameters or arguments are displayed by pressing tab.
While VSCode has a lot of features, I cannot find a similar one for Python.
I found a way for VSCode to show me the definition of the function while hovering in the function itself, but there are no autocompletion for the actual variables of that function (nor suggestions while writing). Besides, the tooltips close itself as soon as I start typing the variables.
Is there a way to get something more similar regarding autocompletion and suggestion of function variables in VSCode while using Python?
Thanks.
According to your description, it is recommended that you use the extension "Pylance", which provides outstanding language service functions.
Its 'Docstrings' and 'auto-completion' functions show us the function parameters and will not close the prompt when inputting:
Part of its function introduction:

How does "Go To Definition" and ”Go to References" works in vscode for Python?

The vscode will record all functions, classes, variables in a table?
Or How does vscode can find definitions and references?
I want to know how VScode build this "Go To Definition" function?
Go to Definition:
If a language supports it, you can go to the definition of a symbol by pressing F12.
If you press Ctrl and hover over a symbol, a preview of the declaration will appear:
Tip: You can jump to the definition with Ctrl+Click or open the definition to the side with Ctrl+Alt+Click.
Go to Type Definition:
Some languages also support jumping to the type definition of a symbol by running the Go to Type Definition command from either the editor context menu or the Command Palette. This will take you to the definition of the type of a symbol. The command editor.action.goToTypeDefinition is not bound to a keyboard shortcut by default but you can add your own custom keybinding.
the explanation is copy pasted from this page:
this
This is a very complicated process and there is a ton of research on software engineering related to this area. Most IDEs/Extensions usually do a best-effort job, and that is good enough for various use cases. It also helps if one follows a widely used build system, and sticks to widely accepted code organization.
Finding definition of a call is a complicated process and usually involve building AST (Abstract Syntax Tree) of the program and finding where a function is defined. There are two important consideration:
type system of the language
organization of code around the build system
For (mostly) statically typed languages like C/C++ etc. finding the function declaration is not too difficult but finding definition usually involves finding where the source file (.c/.cpp) file is? Without the knowledge of build system (cmake, qmake) it is very difficult and hence most IDEs have hard time supporting it.
For languages like rust, where it is customary to follow a rigid system of code organization, simple grepping with some type information is sufficient to get most of the function definitions.
For languages with dynamic type (Python, JavaScript), it is very hard to find the right definition and IDEs/Extensions usually support a well known coding style and module system. TLDR: It helps to follow the crowd in this case. In my experience, PyCharm does a very good job of finding definition of a function invocation.

Can I import and bind python-2.7's function to another function in python-3.x?

Some python-2.7 and python-3.x functions have the same name, but perform differently. Can I import use a py2.7 function in python-3.x one, by changing its name?
The motivating example is python-2.7's "print", i.e. print "TEXT" which does not use without parenthesis, compared to print("TEXT") in python 3. Can I keep the python 2 "print" by binding it to something like pr?
(By the way, the issue for me is typing and escaping the brackets. The keys ( and ) are harder to press than a space bar. Also, because my IDE puts them in automatically, I then need to move my cursor out of it.)
Note: I asked this previously, yet has been wrongly marked as a duplicate.
Again, to be clear, I'm specifically asking if I can bind a python 2 function to a new name in order to use its functionality in python-3.x.
Can I bind python-2.7's `print` in python-3.x, allowing me to use `print` without parenthesis in python-3.x?
I do not know how to contact moderators via internal message or correct this wrongful flag.
The real solution is to configure your IDE, rather than try and hack your way around those configuration problems.
That said, the Python 2 print statement with a space and no parenthesis does not exist in Python 3. While you can find ways to use the function from Python 2, the syntax cannot be used.
If your real problem is with the parentheses in print() for python 3, then no, as far as I know there's not really a solution. If it's a different function, you could always do
def funcName(arg):
return anotherFunc(arg)
or as chepner comments
funcName = anotherFunc
effectively renaming anotherFunc().
As for your IDE specific issues, there's probably a way to turn off the automatic parentheses (or you could just use the arrow keys on your keyboard) and the more you use the parentheses, the faster you'll get using them, which is probably a good thing, as they're used in basically every function you'll ever use.
Finally, it's best not to force a language to do a specific thing that it doesn't really provide for. You don't use GOTOs in Python - they're not built in for a reason. You can write them using other methods. You use parentheses in python 3 - don't try to change that! There's another reason not to alter a language in the way you're describing - it decreases the readability of your code. Everyone will know what you mean when you write
''.join(something)
but not when you write
randomFuncName(something)
and then in some obscure spot you have a function like the one described above that renames ''.join.

Tracking changes in python source files?

I'm learning python and came into a situation where I need to change the behvaviour of a function. I'm initially a java programmer so in the Java world a change in a function would let Eclipse shows that a lot of source files in Java has errors. That way I can know which files need to get modified. But how would one do such a thing in python considering there are no types?! I'm using TextMate2 for python coding.
Currently I'm doing the brute-force way. Opening every python script file and check where I'm using that function and then modify. But I'm sure this is not the way to deal with large projects!!!
Edit: as an example I define a class called Graph in a python script file. Graph has two objects variables. I created many objects (each with different name!!!) of this class in many script files and then decided that I want to change the name of the object variables! Now I'm going through each file and reading my code again in order to change the names again :(. PLEASE help!
Example: File A has objects x,y,z of class C. File B has objects xx,yy,zz of class C. Class C has two instance variables names that should be changed Foo to Poo and Foo1 to Poo1. Also consider many files like A and B. What would you do to solve this? Are you serisouly going to open each file and search for x,y,z,xx,yy,zz and then change the names individually?!!!
Sounds like you can only code inside an IDE!
Two steps to free yourself from your IDE and become a better programmer.
Write unit tests for your code.
Learn how to use grep
Unit tests will exercise your code and provide reassurance that it is always doing what you wanted it to do. They make refactoring MUCH easier.
grep, what a wonderful tool grep -R 'my_function_name' src will find every reference to your function in files under the directory src.
Also, see this rather wonderful blog post: Unix as an IDE.
Whoa, slow down. The coding process you described is not scalable.
How exactly did you change the behavior of the function? Give specifics, please.
UPDATE: This all sounds like you're trying to implement a class and its methods by cobbling together a motley patchwork of functions and local variables - like I wrongly did when I first learned OO coding in Python. The code smell is that when the type/class of some class internal changes, it should generally not affect the class methods. If you're refactoring all your code every 10 mins, you're doing something seriously wrong. Step back and think about clean decomposition into objects, methods and data members.
(Please give more specifics if you want a more useful answer.)
If you were only changing input types, there might be no need to change the calling code.
(Unless the new fn does something very different to the old one, in which case what was the argument against calling it a different name?)
If you changed the return type, and you can't find a common ancestor type or container (tuple, sequence etc.) to put the return values in, then yes you need to change its caller code. However...
...however if the function should really be a method of a class, declare that class and the method already. The previous paragraph was a code smell that your function really should have been a method, specifically a polymorphic method.
Read about code smells, anti-patterns and When do you know you're dealing with an anti-pattern?. There e.g. you will find a recommendation for the video "Recovery from Addiction - A taste of the Python programming language's concision and elegance from someone who once suffered an addiction to the Java programming language." - Sean Kelly
Also, sounds like you want to use Test-Driven Design and add some unittests.
If you give us the specifics we can critique it better.
You won't get this functionality in a text editor. I use sublime text 3, and I love it, but it doesn't have this functionality. It does however jump to files and functions via its 'Goto Anything' (Ctrl+P) functionality, and its Multiple Selections / Multi Edit is great for small refactoring tasks.
However, when it comes to IDEs, JetBrains pycharm has some of the amazing re-factoring tools that you might be looking for.
The also free Python Tools for Visual Studio (see free install options here which can use the free VS shell) has some excellent Refactoring capabilities and a superb REPL to boot.
I use all three. I spend most of my time in sublime text, I like pycharm for refactoring, and I find PT4VS excellent for very involved prototyping.
Despite python being a dynamically typed language, IDEs can still introspect to a reasonable degree. But, of course, it won't approach the level of Java or C# IDEs. Incidentally, if you are coming over from Java, you may have come across JetBrains IntelliJ, which PyCharm will feel almost identical to.
One's programming style is certainly different between a statically typed language like C# and a dynamic language like python. I find myself doing things in smaller, testable modules. The iteration speed is faster. And in a dynamic language one relies less on IDE tools and more on unit tests that cover the key functionality. If you don't have these you will break things when you refactor.
One answer only specific to your edit:
if your old code was working and does not need to be modified, you could just keep old names as alias of the new ones, resulting in your old code not to be broken. Example:
class MyClass(object):
def __init__(self):
self.t = time.time()
# creating new names
def new_foo(self, arg):
return 'new_foo', arg
def new_bar(self, arg):
return 'new_bar', arg
# now creating functions aliases
foo = new_foo
bar = new_bar
if your code need rework, rewrite your common code, execute everything, and correct any failure. You could also look for any import/instantiation of your class.
One of the tradeoffs between statically and dynamically typed languages is that the latter require less scaffolding in the form of type declarations, but also provide less help with refactoring tools and compile-time error detection. Some Python IDEs do offer a certain level of type inference and help with refactoring, but even the best of them will not be able to match the tools developed for statically typed languages.
Dynamic language programmers typically ensure correctness while refactoring in one or more of the following ways:
Use grep to look for function invocation sites, and fix them. (You would have to do that in languages like Java as well if you wanted to handle reflection.)
Start the application and see what goes wrong.
Write unit tests, if you don't already have them, use a coverage tool to make sure that they cover your whole program, and run the test suite after each change to check that everything still works.

Categories