Hi All,
How can i make variable declaration mandatory before i can use it in python?
I don't want my spelling mistakes to introduce any defects in my code
Thanks for reply.
Now as compiler is not warning us,
Whats best way to find out these kind issues which may arise out of spelling mistake or ignorance, to avoid debug time?
If you use Python 3.6 and higher you could use variable annotations, like this
a: int
PyCharm will be able to use it as type hints and produce warnings in case if wrong type used.
What you want is linter, such as
pylint. This won't involve declarations, but it will detect typos much like a language with variable declaration.
Personally, I try to follow a function-programming style of not reassigning variable names. While that won't catch typos in use before runtime, it prevents accidentally naming a second variable with a typo'd name.
You can use this program to print all the names used in your program
"""list_names.py
usage:
python3 list_names.py <FILENAME.PY>
Prints all the non keyword names used in a python program
with their line numbers.
"""
import collections
import keyword
import tokenize
import sys
__version__ = '18.08.26'
def get_name_stats(program):
stats = collections.defaultdict(set)
for tok in tokenize.tokenize(program.readline):
if tok[0] == tokenize.NAME and not keyword.iskeyword(tok[1]):
stats[tok[1]].add(tok[2][0])
return stats
def print_name_stats(program):
stats = get_name_stats(program)
for name in sorted(stats):
print(name, ':', ', '.join(str(x) for x in sorted(stats[name])))
if __name__ == '__main__':
with open(sys.argv[1], 'rb') as program:
print_name_stats(program)
rohitnirantar Wrote:Whats best way to find out these kind issues which may arise out of spelling mistake or ignorance, to avoid debug time?
After many years of python programming, this has never been a serious issue for me.
rohitnirantar Wrote:How can i make variable declaration mandatory before i can use it in python?
Are you a Perl user with the
use strict
directive ? Nothing like this exists in Python, but Python is much less error-prone than Perl.