What type is "if" in python?

Viewed 169
if [conditional]:
    program
else:
    program_alternative

How can I redefine the symbol I use for if? What if I would like to use a unicode character -- is this allowable in python? e.g. ≸ in the place of the string "if".

Is there any way to operate on this syntax? Can I say something like type(if) or perhaps type(__if__)?

I know that python permits variables to have unicode names but what if I especially want to make my code unreadable.

Or, is this something done by the parser that cannot be influenced?

4 Answers

That is correct: "[if is ..] something done by the parser that cannot be influenced".

For clarification, if is a reserved keyword for a specific grammar construct, as defined by the Python language. In general, reserved words cannot be used as identifiers and have special parsing rules and behavior.

As such, type(if) is not even syntactically valid and will fail to parse: the program is invalid / illegal / made-up Python and the presented question of "does if have a type?" is not applicable.

We cannot use a keyword as variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language.

There is no special "if protocol" and __if__ is an undeclared identifier.

In cpython (other implementations may vary, but I doubt in this regard), the if keyword is specified literally in the grammar (for example). Everything else (including the parser) is built from this file.

You could rebuild a cpython interpreter from scratch after changing if to something else... but I'm not sure of the usefulness of it.

See the help at first (unrelated):

>>> help('if')
The "if" statement
******************

The "if" statement is used for conditional execution:

   if_stmt ::= "if" expression ":" suite
               ( "elif" expression ":" suite )*
               ["else" ":" suite]

It selects exactly one of the suites by evaluating the expressions one
by one until one is found to be true (see section Boolean operations
for the definition of true and false); then that suite is executed
(and no other part of the "if" statement is executed or evaluated).
If all expressions are false, the suite of the "else" clause, if
present, is executed.

Related help topics: TRUTHVALUE

>>> 

So anything that that does SyntaxError to you for doing type, means no good type for it, (so basically no-typed)

So See the color of those functions in your interpreter, then remember not to get type out of those :-)

Related