with terminal is there a way for me to get a list of names that are already taken?
like for things like variables and filenames import so I can't accidentally name something that will make a bug
Dani AI
Generated
Good concise summary and a few modern, practical checks that build on the replies from , , , and .
The collision surface to check is threefold: language keywords, builtins, and modules/packages (stdlib + installed). The following terminal one‑liners identify each for a single candidate name (replace 'name' with the identifier to test):
# keyword?
python3 -c "import keyword; print(keyword.iskeyword('name'))"
# builtin?
python3 -c "import builtins; print(hasattr(builtins, 'name'))"
# import resolution (shows where a module would be loaded from, if any)
python3 -c "import importlib.util; s=importlib.util.find_spec('name'); print(s.origin if s else 'not found')" Further useful checks (inspect installed packages and confirm which file would be imported):
# list installed distributions
python3 -m pip list
# import the module and print its file path (if it is a real module)
python3 -c "import importlib; m=importlib.import_module('name'); print(getattr(m,'__file__','built-in'))" Practical safeguards: use a virtual environment to avoid global package collisions; adopt descriptive snake_case names that avoid very short common words; avoid from module import *; run a linter (flake8/pyflakes/pylint) which will flag shadowed builtins or name redefinitions; and if a surprising module is imported, inspect module.__file__ and sys.path to find the offending file. Note the version difference implicit in older replies: some examples in this thread target Python 2 (e.g., reload was built‑in there — in Python 3 use importlib.reload).
Recommended Answers
Jump to Post— Lucaci Andrew 140This is a head start:
Also, dig around a bit, you'll find plenty more, or just hit on google python reserved words/python reserved imports.
As for the imports, before naming a module, make sure you check the name in the documentation,
All 4 Replies
Lucaci Andrew 140 Za s|n
This is a head start:
Also, dig around a bit, you'll find plenty more, or just hit on google python reserved words/python reserved imports.
As for the imports, before naming a module, make sure you check the name in the documentation, Click Here, to see if the name already exist.
Edited by Lucaci Andrew
snippsat 661 Master Poster
dir(__builtins__)
#list of what's in the built-in namespace
If you not sure do a simple test.
You get a NameError if python can't find the name.
>>> reload
<built-in function reload>
>>> my_reload
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'my_reload' is not defined
>>> list
<type 'list'>
>>> lst
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'lst' is not defined
So my_reload and lst is ok names to use.
Also pay attention to modules names,so dont name someting random.py
When Python has a module named random.
Edited by snippsat
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
You can run this simple code ...
''' names_reserved101.py
show all builtin functions/methods and keywords
avoid using any of those names for your variables, or
you will get conflicts, using keywords flag as error
'''
from keyword import kwlist
print("A list of Python's keywords:")
print('\n'.join(kwlist))
print('-'*60)
print("Show all Python builtin functions, classes and alike:")
# does a case insensitive sort first
print('\n'.join(sorted(dir(__builtins__), key=str.lower)))
There is also this ...
print("Show all the modules Python currently knows about:")
help("modules")
chriswelborn 63 ...
Sorry to clutter this question with even more long code, but this is a script I wrote to check modules/classes for builtin conflicts. It searches the current directory for modules or can be used on other directories by adding to sys.path.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def main(argz):
addsyspath = argz[1] if len(argz) > 1 else None
moduleorclass = argz[0][:-3] if argz[0].endswith(".py") else argz[0]
print "current dir: " + sys.path[0]
if addsyspath is not None:
print "adding sys path: " + str(addsyspath)
shortname = moduleorclass.split('.')[-1]
print "checking: " + shortname + '\n'
# retrieve list of conflicts
try:
conflicts = runtest(moduleorclass, addsyspath)
# print results
if len(conflicts) == 0:
print "no conflicts found."
else:
print "found " + str(len(conflicts)) + " conflicts:"
print " " + "\n ".join(conflicts) + '\n'
except Exception as ex:
print "error checking: " + shortname + '\n' + str(ex)
return 1
# success
print "finished.\n"
return 0
def runtest(module_name, new_syspath=None):
""" module_name : (string) Full module name or class to import ("mymodule.submodule.classname")
new_syspath : (string) Path to add to sys.path (/path/to/module)
Imports a module by string name, inserts syspath if wanted, and does getconflicts() on it.
"""
# add python path (if it was passed)
if new_syspath is not None:
sys.path.insert(0, new_syspath)
# trim .py extension (if it wasn't already)
if module_name.endswith(".py"): module_name = module_name[:-3]
# import module to check builtins.
exec("import " + module_name)
imp_ = eval(module_name)
# test conflicts and return them
return getconflicts(imp_)
def getconflicts(module_class):
""" runs conflict test on already imported module or class, returns list """
# test conflicts
conflicts = []
for i in dir(__builtins__):
# test item, filter certain items.
if ((i in dir(module_class)) and
(not i.startswith("__"))):
# filter __item__'s...
conflicts.append(str(i))
return conflicts
# ----- START OF SCRIPT
if __name__ == "__main__":
args = sys.argv[1:]
if ((len(args) == 0) or
("-h" in args) or
("--help" in args)):
# no args, or help flags.
print "usage: pyconflicts.py <modulename.or.class> [<python path to add>]\n" + \
" example:\n" + \
" ./pyconflicts.py myscript\n" + \
" ./pyconflicts.py myproject.myclass /path/to/myproject\n"
ret = 1
else:
# have args, run it.
ret = main(args)
# exit with return code.
sys.exit(ret)
If the name of this script is 'pyconflicts.py' you would run it like this:
./pyconflicts.py myscript
./pyconflicts.py myscript.myclass
** notice no .py extension, name it like you were going to import it.
./pyconflicts.py myotherscript /path/to/myotherdir
** if myotherscript is in a different directory, you will need to add that dir to python path.
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.