tags:

views:

146

answers:

3

I'm working through a Python 3 book and came across the string function isidentifier(). The text description is "s.isidentifier() : Returns True if s is non empty and is a valid identifier". I tested it in the Python Shell like this:

>>> s = 'test'
>>> s.isidentifier()
True
>>> 'blah'.isidentifier()
True

I would expect the 2nd statement to return false since 'blah' is not held in a variable. Can anyone explain this? Thanks.

+5  A: 

Returns True if s is non empty and is a valid identifier.

What they mean is that s could be valid as an identifier. It doesn't imply that it is an identifier that's in use.

Your first example is showing the same thing: 'test' (what isidentifier is actually checking) is not the name of a variable either. I think you meant

>>> 's'.isidentifier()
True
Matthew Crumley
To write what rosscj2533 *thought* it was, I guess you could do isidentifier() first and then do an eval() and see if it gives you a NameError or not.
MatrixFrog
Ah, I was taking it as is currently a valid identifier that's in use. Thanks.
rosscj2533
@MatrixFrog - much better to test for existence of this identifier in locals() and globals(), rather than eval()'ing it. Faster *and* safer.
Paul McGuire
+2  A: 

"isidentifier" doesn't say anything about the "variable" the string being tested is referenced by. So

'blah'.isidentifier()

is identical to

s = 'blah'
s.isidentifier()

In Python, it's never (or rarely) about the "variable" (Python doesn't have variables), it's about the object. In this case, strings.

jae
+1  A: 

Python doesn't have "variables". It is more helpful to think in terms of objects.

'blah' definitely exists at the time 'blah'.isidentifier() is called (after all it means that "call isidentifier() method of the string object 'blah'").

So if your understanding were correct, isidentifier() method of string objects should always return True, because at the time of the call, the object definitely exists.

What isidentifier() does is to check that the string object can be used as a valid identifier. Try these two lines in your Python session for example:

>>> a = "$"
>>> "$".isidentifier()

Even though "$" is assigned to the name a, the isidentifier() call returns False since $ is not a valid identifier in Python.

Alok