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

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

Related

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

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

Non-ASCII Python identifiers and reflectivity [duplicate]

This question already has answers here:
Identifier normalization: Why is the micro sign converted into the Greek letter mu?
(2 answers)
Closed 5 years ago.
I have learnt from PEP 3131 that non-ASCII identifiers were supported in Python, though it's not considered best practice.
However, I get this strange behaviour, where my 𝜏 identifier (U+1D70F) seems to be automatically converted to τ (U+03C4).
class Base(object):
def __init__(self):
self.𝜏 = 5 # defined with U+1D70F
a = Base()
print(a.𝜏) # 5 # (U+1D70F)
print(a.τ) # 5 as well # (U+03C4) ? another way to access it?
d = a.__dict__ # {'τ': 5} # (U+03C4) ? seems converted
print(d['τ']) # 5 # (U+03C4) ? consistent with the conversion
print(d['𝜏']) # KeyError: '𝜏' # (U+1D70F) ?! unexpected!
Is that expected behaviour? Why does this silent conversion occur? Does it have anything to see with NFKC normalization? I thought this was only for canonically ordering Unicode character sequences...
Per the documentation on identifiers:
All identifiers are converted into the normal form NFKC while parsing;
comparison of identifiers is based on NFKC.
You can see that U+03C4 is the appropriate result using unicodedata:
>>> import unicodedata
>>> unicodedata.normalize('NFKC', '𝜏')
'τ'
However, this conversion doesn't apply to string literals, like the one you're using as a dictionary key, hence it's looking for the unconverted character in a dictionary that only contains the converted character.
self.𝜏 = 5 # implicitly converted to "self.τ = 5"
a.𝜏 # implicitly converted to "a.τ"
d['𝜏'] # not converted
You can see similar problems with e.g. string literals used with getattr:
>>> getattr(a, '𝜏')
Traceback (most recent call last):
File "python", line 1, in <module>
AttributeError: 'Base' object has no attribute '𝜏'
>>> getattr(a, unicodedata.normalize('NFKD', '𝜏'))
5

Print an object's attributes like json.dumps prints a dict [duplicate]

This question already has answers here:
Is there a built-in function to print all the current properties and values of an object?
(30 answers)
Closed 7 years ago.
EDIT: a solution is in this answer: How to use a dot “.” to access members of dictionary?
When using a dict:
d = dict()
d['param1'] = 17
d['param2'] = 3
it's easy to print it with print json.dumps(d). When using an object / class:
class z:
pass
z.param1 = 17
z.param2 = 3
I can't manage to print all the attributes of z, neither with print json.dumps(z), nor with print z. How to do it?
Sidenote but important: why do I want to use a class / object to store parameters, when it would be logical to use a dict? Because z.param1 is much shorter and handy to write than z['param1'], especially with my (french) keyword [, ], 'are quit long to write because ALT+GR+5 (let's say 2 seconds instead of 0.5, but this really matters when you have a long code with many variables)
You may simply use __dict__ on a class instance to get the attributes in the form of dict object as:
>>> z.__dict__
>>> {'param1': 17, '__module__': '__main__', 'param2': 3, '__doc__': None}
However, if you need to remove the __xxx__ inbuilt methods then you may need to specify the __str__ method inside the class.

What Is Subscriptable? [duplicate]

This question already has answers here:
l.append[i], object is not subscriptable? [closed]
(2 answers)
Closed 8 years ago.
exxy = ['mix', 'xyz', 'aardvark', 'xanadu', 'apple']
pleasework = []
ten = []
for s in exxy:
if s[0] == 'x':
pleasework.insert[0, s]
else:
ten.append[s]
pleasework.sort()
ten.sort()
pleasework.append(ten)
print pleasework
I keep getting an error that says that object is not subscriptable.
Traceback (most recent call last):
File "/Users/jerrywalker/Desktop/CompSci/Programming/Programming_Resources/Python/idle.py", line 10, in <module>
ten.append[s]
TypeError: 'builtin_function_or_method' object is not subscriptable
I'm not really sure what this means. I've just started Python yesterday... I'm sure it's something in the code that I'm not doing right, because even when I change the name of my variables around the error is the same.
"Subscriptable" means that you're trying to access an element of the object. In the following:
ten.append[s]
you're trying to access element s of ten.append. Since you want to call it as a function/method instead, you need to use parens:
ten.append(s)
You have defined two lines with the wrong syntax:
It shouldn't be:
pleasework.insert[0, s]
ten.append[s]
But rather:
pleasework.insert(0, s)
ten.append(s)
ten.append(s) is a list method and you cannot try to get a element s of ten.append(s).
Even assuming you were trying to do something like ten[s] it would still return a error because s has to be the index (which is a integer) of the element you want

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