Is 'input' a keyword in Python? - python

I'm new to Python. I'm writing some code in Sublime and it highlights the word 'input'
I use it as a variable name and it seems to work, so I wondered whether it may be a keyword in a newer version. (I'm currently using 2.7.5)

No, input is not a keyword. Instead, it is a built-in function.
And yes, you can create a variable with the name input. But please don't. Doing so is a bad practice because it overshadows the built-in (makes it unusable in the current scope).
If you must use the name input, the convention is to place an underscore after it:
input_ = input()

input is not a keyword, it's a function provided by the standard library and included in the builtins module (this module provides globally accessible variables and functions.):
>>> import builtins
>>> input is builtins.input
True
And sure, you can create a variable with the name input. It's perfectly fine for experienced and intermediate users to do so because they can easily figure that the input name has been re-used.
Use the best name for the content/intent you want to convey. If input is the best then use it (provided you don't need the builtin), and don't confuse readers with names like input_ (beginners will wonder whether there's a special meaning to a trailing underscore)
But if you're a beginner please don't re-define builtins, by overshadowing the built-in input (overshadowing a variable makes it unusable in the current scope) you'll end-up with this error when calling input() later on (in the same scope) and you may struggle to figure out why:
TypeError: 'str' object is not callable
Beginners should instead use another name, preferably not input_ because underscores have special meanings in python, as a result other beginners will wonder whether there's a special meaning for that trailing underscore (is it the same or related to leading underscores? or maybe to double underscores?)
In another comment someone stated that it is a bad practice to overshadow variables and he even came up with a convention that he borrowed from another use. After all, if overshadowing variables were a really bad practice, the python language designers wouldn't have allowed it in the first place, but they know and recognize that it has the potential to improve readability, just as it does in other languages. So they allowed it, and it also ease transition to Python from other languages where overshadowing is also allowed like C/C++, Java and even bash.
note: the conventional use for a trailing underscore is where it's impossible to use a name, like the keyword class in Python. Then you'd use class_ (but like I wrote above, it's best to avoid it in Python because underscores can confuse beginners as they can convey special meanings)

Related

Why classes like `list`, `str` starting from small letters and other has camel case fonting [duplicate]

Often when I see class definitions class Foo:, I always see them start with upper case letters.
However, isn't a list [] or a dict {} or some other built-in type, a class as well? For that matter, everything typed into the Python's IDLE which is a keyword that is automatically color coded in purple (with the Window's binary distribution), is itself a class, right?
Such as spam = list()
spam is now an instance of a list()
So my question is, why does Python allow us to first of all do something like list = list() when nobody, probably, does that. But also, why is it not list = List()
Did the developers of the language decide not to use any sort of convention, while it is the case that most Python programmers do name their classes as such?
Yes, uppercase-initial classes are the convention, as outlined in PEP 8.
You are correct that many builtin types do not follow this convention. These are holdovers from earlier stages of Python when there was a much bigger difference between user-defined classes and builtin types. However, it still seems that builtin or extension types written in C are more likely to have lowercase names (e.g., numpy.array, not numpy.Array).
Nonetheless, the convention is to use uppercase-initial for your own classes in Python code.
PEP8 is the place to go for code style.
To address your question on why list = list() is valid, list is simply a name in the global namespace, and can be overriden like any other variable.
All are in the end design decisions.
[...] why does python allow us to first of all do something like list = list()
https://www.python.org/dev/peps/pep-0020/ says (try also >>> import this)
Simple is better than complex.
Special cases aren't special enough to break the rules.
And this would be a special case.
[...] why is it not list = List()
https://www.python.org/dev/peps/pep-0008/#class-names says:
Class Names
Class names should normally use the CapWords convention.
The naming convention for functions may be used instead in cases where
the interface is documented and used primarily as a callable.
Note that there is a separate convention for builtin names: most
builtin names are single words (or two words run together), with the
CapWords convention used only for exception names and builtin
constants. [emphasis mine]
All other classes should use the CapWorlds convention. As list, object, etc are built-in names, they follow this separate convention.
I think that the only person who really knows the entire answer to your question is the BDFL. Convention outside of the types implemented in C is definitely to use upper-case (as detailed in PEP8). However, it's interesting to note that not all C-level types follow the convention (i.e. Py_True, Py_False) do not. Yes, they're constants at Python-level, but they're all PyTypeObjects. I'd be curious to know if that's the only distinction and, hence, the difference in convention.
According to PEP 8, a nice set of guidelines for Python developers:
Almost without exception, class names use the CapWords convention.
Classes for internal use have a leading underscore in addition.
PEP 8 is directed at Python development for the standard library in the main Python distribution, but they're sensible guidelines to follow.

proper way to name a variable already used?

in python (3.3.3), what is the proper way to name a variable that is already being used?
for example, I want to create the variable input. obviously this will not work as there is a python keyword called input.
assuming I needed a name similar to input, what is the proper way to name it without deviating much from the word input, that is, not using a name like user_input or answer?
You can use any name even if it is used by a function.
What you can't is use keywords like def, class, if, else...
But of course it is not a good practice to replace those names used by functions to avoid confusion.
A known practice is to add a _ to the end: input_, class_...

Function Call Variables Same as In Function

I am somewhat new to Python--beginner moving to intermediate--and would like to know how more experienced Python coders name their call and function variables.
Specifically, I like to name the call variables the same as the called function's 'receive' variables. Ditto the return variables.
Works fine, but are there problems I could run into, outside of changing a variable to global in the future?
An example call: v_Array = f_InitSpecified2DArray(v_Width,v_Length)
The example called or 'receiving' function: def f_InitSpecified2DArray(v_Width, v_Length):
And I do the same in the return as well: return v_Array
def f_InitSpecified2DArray(v_Width, v_Length):
v_Array = [v_Width, v_Length]
return v_Array
v_Array = f_InitSpecified2DArray(v_Width,v_Length)
The question is: Shall I expect any conflict resulting from reuse of name v_Array inside the function return and later in the calling code, where it goes assigned into variable with the same name v_Array?
Thanks.
No, this will not cause you difficulties, and doesn't cause confusion - for you, your readers, or the Python interpreter. Certainly it's less confusing than making up a new name just to differ from the parameter name, which is unnecessary. In fact, you'll often encounter the same name being used for both a named parameter and its argument, as in
runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
which comes from doctest.py in the standard library (for Python 3.3).
It's instructive to search the standard library for this pattern, <name>=<same_name> (abuse of notation which I'll rectify in a moment), as its occurrences are examples of just what you're asking about. On OS X and Linux, the following command will show all lines in the standard library (plus site-packages) with occurrences of the pattern:
grep -Er --include=*.py '(\b[[:alnum:]]+\b)=\1\b' /path/to/pythonlib
On a Mac, for example, /path/to/pythonlib for Python 3.3 is usually /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3.
This command shows how many lines feature the construct, many of which have multiple occurrences:
grep -Er --include=*.py '(\b[[:alnum:]]+\b)=\1\b' /path/to/pythonlib | wc -l
I get a count of 1129, which includes a few dozen in my site-packages subdirectory. In other words, it's quite common.
Read PEP 008 titled "Style Guide for Python Code"
You seem to search for something more precise and systematic, this I appreciate, but you will safe a lot of effort and confusion to yourself and others dealing with your code, if you try to folow the PEP 008.
As usual, you will not find it followed everywhere, but that is life.
To your question about function names and variables - PEP 008 recommends using lowercase names with words separated by underscore.
local variable names are irrelevant, it really does not matter what variable name you use for return.
And do not plan moving variables into global scope too early, you shall in fact working in the other direction.

iterate a list when list name is dynamically generated

How do I iterate through a list whose name will be dynamically generated?
boneList_head =['def_neck', 'def_armbase']#hard coded list
itemType='head'# result of a user button press
...
def selectBones():
global itemType
bones =('boneList_'+itemType)# evaluates as a string , not name of a list
for bone in bones:
cmds.select(bone, tgl=True)
the problem is bones is getting evaluated as a string, when I need it to evalute as the name of a list.
Dynamically generating variable names is almost always a bad approach. Use a dictionary!
bonedict = {'boneList_head': ['def_neck', 'def_armbase']}
itemType='head'
def selectBones(itemType):
bones = bonedict['boneList_' + itemType]
for bone in bones:
cmds.select(bone, tgl=True)
Please ignore my previous answer (visible in my edit history) which was stupid -- boneheaded, even. But I blame its stupidity on dynamic variable name generation!
Let me elaborate on why dynamic variable name generation is a bad idea.
Because dynamic variable generation masks variable name definitions. It's hard to tell what has been defined and what hasn't, so it's easy to accidentally redefine a variable. This is a major source of potential bugs.
Because dynamic variable manipulation hides state changes under another layer of obfuscation. To some degree, this is true anytime you create a dictionary or a list. But one expects lists and dictionaries to demand a little extra thinking. Variable names, on the other hand, should be dead simple. When variable definitions and redefinitions require deep thought to understand, something is wrong.
Because dynamic variable generation pollutes the namespace. If you have so many variables that you have to automatically generate them, then they should live in their own namespace, not in the locals of a function, and definitely not in the global namespace. In his style guide for the linux kernel, Linus Torvalds advises that if a function has more than 5-10 local variables, you're doing something wrong.
Because dynamic variable generation contributes to high coupling, which is a bad thing. If you assign to values to a dictionary, you can pass that dictionary back and forth until the cows come home, and all anyone has to know about is that dictionary. If you dynamically create variable names in the global namespace of a module, then if another module wants to access those variable names, it has to know all about the way they were generated, what other variables in that module are defined, and so on. Also, passing the variables around becomes much more complex -- you have to pass around a reference to the module itself, probably using sys.modules or other questionable constructs.
Because dynamic variable generation is ugly. eval looks neat and clean, but it really isn't. It can do anything. Functions that can do anything are bad, because you can't tell at first glance what they're doing here. A well-defined function does one thing, and does it well; that way, whenever you see that function, you know exactly what's happening. When you see eval, literally anything could be happening. In this sense, eval is like goto. The problem with goto is not that you can't use it correctly; it's that for every possible correct use of goto, there are 500,000,000 terrifyingly wrong ways to use it. I won't even discuss the security problems here, because in the end, that's not the real problem with eval.
I agree with the other comments that your approach is probably not the best. But the following should work:
bones = eval('boneList_' + itemType)
This will run the python interpreter on "boneList_head", and return the list.
NOTE: As Adam Mihalcin mentioned in the comments, you should be very careful about only running eval on data that you trust or have validated. A malicious user could inject arbitrary code into the itemType variable to access the os, etc.
This is an ugly hack, but it works...(of course, you need to get the correct module)
import sys
boneList_head =['def_neck', 'def_armbase']
itemType='head'
...
def selectBones():
global itemType
bones=vars(sys.modules["__main__"])['boneList_'+itemType]
for bone in bones:
cmds.select(bone, tgl=True)
This really isn't different than what other people are saying however-- We're using vars to construct a dictionary to get the list you want -- why not just pass a dictionary (or the correct list) to the function selectBones in the first place?

Arguments, local variables, and global variables coding convention in Python

In python, there is no way to differentiate between arguments, local variables, and global variables. The easy way to do so might be have some coding convention such as
Global variables start with _ and capital letter
arguments end with with _
_Gvariable = 10
def hello(x_, y_):
z = x_ + y_
Is this a Pythonian way to go? I mean, is there well established/agreed coding-standards to differentiate them in python?
=== ADDED ===
I just want to discriminate between arguments and local variables. As arguments are given from outside, and more like a ROM in the sense that it is not assumed to be read only.
C++ provides the const keyword to prevent the arguments from changing, but not for python. I thought appending _ can be one of a way to mimic this feature in python.
I would do all your python programming according to PEP 8 guidelines. Anyone who has to read your code will thank you for it.
http://www.python.org/dev/peps/pep-0008/
Why is there a need to distinguish between arguments and local variables, since one is merely a subset of the other. You can use locals(), globals(), and vars() to view scope if you are having local-global issues. The inspect module can help with that, too. And if possible, avoid using global variables as much as possible.
It is usually obvious in python which variables are local and which are global, since to modify a global variable you have to declare it using the the global keyword at the start of a function. However I sometimes add a global declaration even if it is not necessary for python to compile it, in order to emphasize that an object is global - e.g. modifying a mutable global data-structure.
Arguments should be obvious because they are in the function declaration.
As others have said constants should be in UPPER_CASE_WITH_UNDERSCORES, which is a convention shared by many languages.
If you find that you are having trouble keeping track of which are global, local and parameter variables I suggest that the problem may be your functions are too long and doing too much. Functions & methods should be short and do exactly one thing. I start to get the refactoring itch if my functions go over about 10-20 lines of code.
I recommend reading the book Clean Code by Robert Martin. The examples are in Java, but the principles apply to all languages.
That's absolutly awful. There is no reason whatsoever to use a special naming scheme for global and local objects. Also you should avoid having global objects unless they are functions, classes or constants.
Names for constants should be uppercase and seperated with underscores LIKE_THIS, class names look LikeThis and functions and method names should look like any other name. Names for objects which are implementation specific, can be changed/removed at any time or can not be relied on for any other good reasons should be prefixed with an underscore.
You should also read the Python styleguide PEP 8 which covers these and more style-related rules you should follow as long as it doesn't make your code less readable. Most Python projects follow this or at least a compatible version of this style guide.
Local variables are variables that are declared inside a function.
Global variables are variables that are declared outside a function.
For Example:
global_var = 5 #Global Variable
def add(a,b):
local_var = a+b #Local Variable
print("The sum is",local_var)
print("The global variable is",global_var)
add(10,20)

Categories

Resources