Can keywords will be used as identifier in Python? [duplicate] - python

This question already has answers here:
What are "soft keywords"?
(3 answers)
Closed 2 months ago.
Can keywords be used as identifiers in Python?
Please explain about keywords and identifiers
can we use it in all workstation?
Yes or No
If yes then how?
If No then how?

Pretty easy to find the answer to this question:
>>> class = 56
File "<stdin>", line 1
class = 56
^
SyntaxError: invalid syntax
>>> def = 42
File "<stdin>", line 1
def = 42
^
SyntaxError: invalid syntax
No, you cannot use keywords as variable names.
However, you can use the names of built-in types as variable names. It shows up on SO all the time, and it's a very bad idea because that built-in type then becomes unavailable.
E.g.
>>> from collections import defaultdict
>>> list = [42, 27]
>>> d = defaultdict(list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: first argument must be callable or None

Related

What does "a: 5" without curly braces mean? [duplicate]

This question already has answers here:
Use of colon in variable declaration [duplicate]
(1 answer)
What is this odd colon behavior doing?
(2 answers)
Closed 12 months ago.
I noticed that if I type, for instance >>> a: 5 as input of the python interpreter, it does not return an error (whether or not the variable 'a' is already defined). However, if I type >>> a afterwards, I get the usual NameError.
My question is: what does the python interpreter do when I type this kind of dictionary syntax without the curly braces?
Originally, I found this syntax in matplotlib's matplotlibrc file (see here).
It defines a type hint. But without a value, the variable will not be initialized in the global scope.
>>> a: int = 3
>>> globals()['__annotations__']
{'a': <class 'int'>}
>>> a
3
>>> b: str
>>> globals()['__annotations__']
{'a': <class 'int'>, 'b': <class 'str'>}
>>> b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
a: 5 in the interpreter uses the type hint syntax, but this has nothing to do with what you see in matplotlib's documentation that defines a configuration file (and thus is not python code).
from the documentation:
You can create custom styles and use them by calling style.use with the path or URL to the style sheet.
For example, you might want to create ./images/presentation.mplstyle with the following:
axes.titlesize : 24
axes.labelsize : 20
lines.linewidth : 3
lines.markersize : 10
xtick.labelsize : 16
ytick.labelsize : 16
The above is not python code

Is it possible to use a class as a dictionary key in Python 3?

I'm trying to reduce copy/paste in my code and have stumbled upon this problem. I've googled for the answer but all answers use an instance of a class as the key, I can't find anything on using a class definition itself as the key (I don't know if it's possible).
My code is this:
# All chunkFuncs keys are class definitions, all values are functions
chunkFuncs = {Math_EXP : Math_EXPChunk, Assignment : AssignmentChunk, Function : FunctionChunk}
def Chunker(chunk, localScope):
for chunkType in chunkFuncs:
if isinstance(chunk,chunkType):
# The next line is where the error is raised
localScope = chunkFuncs[chunk](chunk,localScope)
return localScope
and the error is this
TypeError: unhashable type: 'Assignment'
Here are the class definitions:
class Math_EXP(pyPeg.List):
grammar = [Number,Symbol],pyPeg.maybe_some(Math_OP,[Number,Symbol])
class Assignment(pyPeg.List):
grammar = Symbol,'=',[Math_EXP,Number]
class Function(pyPeg.List):
grammar = Symbol,'(',pyPeg.optional(pyPeg.csl([Symbol,Number])),')'
Are there any alternative methods I could use to get the same effect?
Thanks.
OK, the comments are getting out of hand ;-)
It seems certain now that the class object isn't the problem. If it were, the error would have triggered on the first line, when the dict was first constructed:
chunkFuncs = {Math_EXP : Math_EXPChunk, Assignment : AssignmentChunk, Function : FunctionChunk}
If you try to construct a dict with an unhashable key, the dict creation fails at once:
>>> {[]: 3}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
But you got beyond that line, and Assignment is a key in the dict you constructed. So the error is in this line:
localScope = chunkFuncs[chunk](chunk,localScope)
Best guess is that it's an instance of Assignment that's unhashable:
>>> class mylist(list):
... pass
...
>>> hash(mylist)
2582159
>>> hash(mylist())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'mylist'
See? mylist is hashable, but the instance mylist() is not.
Later: best guess is that you're not going to be able to worm around this. Why? Because of the name of the base class, pyPeg.List. If it's mutable like a Python list, then instances won't be hashable - and shouldn't be (mutable objects are always dangerous as dict keys). You could still index a dict by id(the_instance), but whether that's semantically correct is something I can't guess without knowing a lot more about your code.
You should be able to, yes, but you might need an extra type call:
>>> class X:
... pass
...
>>> class_map = {X: 5}
>>> my_x = X()
>>> class_map[type(my_x)]
5

python TypeError: frozenset expected at most 1 arguments, got 4

I'm getting this error when trying to make a frozen set:
class Transcriber:
DNA_BASES = frozenset('A','T','G','C')
...
And this is the Traceback:
~/python/project5$ python wp_proj5.py
Traceback (most recent call last):
File "wp_proj5.py", line 5, in <module>
class Transcriber:
File "wp_proj5.py", line 7, in Transcriber
DNA_BASES = frozenset('A','T','G','C')
TypeError: frozenset expected at most 1 arguments, got 4
What is wrong here? Can't I initialize a frozenset with more than one string?
You need to pass an iterable like a list:
frozenset(['A','T','G','C'])
You can read about it here: http://docs.python.org/2/library/stdtypes.html#frozenset

Cases where use of tuple is a must

In Python, the only difference between a list and a tuple that I know of is "lists are mutable but tuples are not". But as far as I believe, it depends on whether the coder wants to risk mutability or not.
So I was wondering whether there are any cases where the use of a tuple over a list is a must. Things that can not be done with a list but can be done with a tuple?
You can use tuples as keys in dictionaries and insert tuples into sets:
>>> {}[tuple()] = 1
>>> {}[list()] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Which is basically a result of a tuple being hashable while a list isn't:
>>> hash(list())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(tuple())
3527539
The answer by #Otto is very good. The only thing I have to add to it is that when you open things up to 3rd party extensions, you really need to consult the documentation. Some functions/methods may expect one or the other data-type (or have different results depending on which one you use). One example is using tuples/lists to index a numpy array:
import numpy as np
a=np.arange(50)
a[[1,4,8]] #array([1, 4, 8])
a[(1,4,8)] #IndexError
EDIT
Also, a quick timing test shows that tuple creation is MUCH FASTER than list creation:
import timeit
t=timeit.timeit('[1,2,3]',number=10000000)
print (t)
t=timeit.timeit('(1,2,3)',number=10000000)
print (t)
which is good to keep in mind. In other words, do:
for num in (8, 15, 200):
pass
instead of:
for num in [8, 15, 200]:
pass
Also, the now obsolete string formatting using the % operator requires the argument list to be a tuple. A list would be treated as single argument:
>>> "%s + %s" % [1, 2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s + %s" % (1, 2)
'1 + 2'

Add custom method to string object [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Can I add custom methods/attributes to built-in Python types?
In Ruby you can override any built-in object class with custom method, like this:
class String
def sayHello
return self+" is saying hello!"
end
end
puts 'JOHN'.downcase.sayHello # >>> 'john is saying hello!'
How can i do that in python? Is there a normally way or just hacks?
You can't because the builtin-types are coded in C. What you can do is subclass the type:
class string(str):
def sayHello(self):
print(self, "is saying 'hello'")
Test:
>>> x = string("test")
>>> x
'test'
>>> x.sayHello()
test is saying 'hello'
You could also overwrite the str-type with class str(str):, but that doesn't mean you can use the literal "test", because it is linking to the builtin str.
>>> x = "hello"
>>> x.sayHello()
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
x.sayHello()
AttributeError: 'str' object has no attribute 'sayHello'
>>> x = str("hello")
>>> x.sayHello()
hello is saying 'hello'
The normal Python equivalent to this is to write a function that takes a string as it's first argument:
def sayhello(name):
return "{} is saying hello".format(name)
>>> sayhello('JOHN'.lower())
'john is saying hello'
Simple clean and easy. Not everything has to be a method call.

Categories

Resources