Joachim W
Joachim W

Reputation: 8167

Python: are there ways to detect missing () in method call?

I want to call a method f(), but accidentally I just say f. Python3 mistakes this for a meaningless evaluation of a nonexisting variable, and therefore skips over my intended method call without any notice. Is there a way to override this default behavior and to get an error message? Either by forbidding dual use of an identifier as a method and as a variable, or by forbidding a meaningless statement consisting just of an identifier?

Upvotes: 4

Views: 221

Answers (4)

Colonel Panic
Colonel Panic

Reputation: 137604

Alas, no. Python doesn't have any strict warning modes (cf. Perl and Ruby). Besides, such lines are valid statements, so it wouldn't be fair to warn against them.

You could write your own code checker to find lines like these though. Search for lines that are a single word without any punctuation, and that are a Python identifier (not a keyword such as break)

Upvotes: 0

John Szakmeister
John Szakmeister

Reputation: 47032

It's valid syntax, so Python won't complain. You may want to consider some other tools, like pylint. Pylint would've reported:

W:  4,0: Statement seems to have no effect

If you simply did:

f

instead of:

f()

The only catch is the pylint can complain an awful lot out of the box. Make sure to create a config that is tolerant of your style.

Upvotes: 5

John La Rooy
John La Rooy

Reputation: 304255

The usual way to make sure your code does what it is supposed to is to write unit tests. This type of bug cannot slip by if you have good test coverage.

Passing references to functions/methods is quite common (and useful) in Python, so it's not something you should want to disable.

Upvotes: 1

TyrantWave
TyrantWave

Reputation: 4673

In [1]: def f():
   ...:     print("This is some random function")
   ...:     return

In [2]: a = f

In [3]: a()
This is some random function

In [4]: somedict = {"call_something": f, "call_another": a}

In [5]: somedict["call_something"]()
This is some random function

In [6]: f
Out[6]: <function __main__.f>

Using a function without calling it is completely valid syntax, and has various uses as I've just shown. It's not a meaningless evaluation of a nonexisting variable, because functions are variables essentially.

Upvotes: 3

Related Questions