I am using Python 3.6.1, and I have come across something very strange. I had a simple dictionary assignment typo that took me a long time to find.
context = {}
context["a"]: 2
print(context)
Output
{}
What is the code context["a"]: 2
doing? It doesn't raise a SyntaxError
when it should IMO. At first I thought it was creating a slice. However, typing repr(context["a"]: 2)
raises a SyntaxError
. I also typed context["a"]: 2
in the console and the console didn't print anything. I thought maybe it returned None
, but I'm not so sure.
I've also thought it could be a single line if statement, but that shouldn't be the right syntax either.
Additionally, context["a"]
should raise a KeyError
.
I am perplexed. What is going on?
duplicated() function indicate duplicate Series values. The duplicated values are indicated as True values in the resulting Series. Either all duplicates, all except the first or all except the last occurrence of duplicates can be indicated. Example #1: Use Series.
In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object.
For copying mutable objects like lists or dictionaries, we use copy() method. When invoked on any object, the copy() method creates a new object with the same data as the original object and returns a reference to it.
You have accidentally written a syntactically correct variable annotation. That feature was introduced in Python 3.6 (see PEP 526).
Although a variable annotation is parsed as part of an annotated assignment, the assignment statement is optional:
annotated_assignment_stmt ::= augtarget ":" expression ["=" expression]
Thus, in context["a"]: 2
context["a"]
is the annotation target2
is the annotation itselfcontext["a"]
is left uninitialisedThe PEP states that "the target of the annotation can be any valid single assignment target, at least syntactically (it is up to the type checker what to do with this)", which means that the key doesn't need to exist to be annotated (hence no KeyError
). Here's an example from the original PEP:
d = {}
d['a']: int = 0 # Annotates d['a'] with int.
d['b']: int # Annotates d['b'] with int.
Normally, the annotation expression should evaluate to a Python type -- after all the main use of annotations is type hinting, but it is not enforced. The annotation can be any valid Python expression, regardless of the type or value of the result.
As you can see, at this time type hints are very permissive and rarely useful, unless you have a static type checker such as mypy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With