I'm used to a firm distinction between identifiers (variable names) and strings in programming languages.
Yet Python has some malleability between the two. For example in the code
import networkx as nx
G = nx.Graph()
G.add_edge(1, 2, food='eggs')
for node1, node2, data in G.edges(data=True):
print(data['food'])
we use food
as an identifier on line 3 and then as the string 'food'
when we retrieve the attribute on line 5.
I'd like to better understand what is happening. What is the feature in a programming language generally and in Python specifically that makes this malleability possible?
(Please note that NetworkX is incidental to the question, which is why I'm not listing it in the keywords.)
Clarification why this question is not asking for an explanation of—and is all but superficially related to keyword arguments:
Sometimes what is happening is perfectly clear. For example if we write the code
def foo(bar, baz):
pass
foo(1, 2)
foo(baz=2, bar=1)
(using keyword arguments in whichever order we like), the Python interpreter would have seen the names (not the strings) bar
and baz
and is henceforth expecting names (not strings) bar
and baz
, in any order.
But in other contexts this malleability is truly puzzling. For example in the following code explaining keyword arguments
def my_function(**kwargs):
print str(kwargs)
my_function(a=12, b="abc")
{'a': 12, 'b': 'abc'}
we introduce keyword arguments in the function call, only, lo and behold, to find that they have become strings.
From an answer to the present question
>>> d = dict(food='eggs')
>>> d['food']
'eggs'
it becomes clear that in Python there is zero distinction between d1
and d2
whether we write:
d1 = {'food':'eggs'}
or
d2 = dict(food='eggs')
What happens with d1
makes perfect sense. The type of 'food'
is a string.
But, again, d2
is obscure. Although we end up with exactly the same outcome, the language has somehow molded the identifier/name that we used (food
) into a string.
What is the feature of programming languages generally and Python specifically that permits a language to mold a name into a string? Now that a pattern is emerging, might it be the case that Python uses some mechanism for switching names into strings, but there are no instances of switching strings to identifiers?