Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function syntax seems to be invalid, but runs

All, I've run across a weird surprise in python today. The following code works, but seems to violate python's syntax. I don't know why it would work without a pass statement, or some code, but it does.

def test():
    '''Sample docstring.'''

for i in range(10):
    test()
    print "testing", i

I'd like to determine why this works, and if it leaves any nasty bits in memory while it runs. It may be the cause of a memory issue I've been trying to track down.

like image 926
Spencer Rathbun Avatar asked Dec 04 '25 19:12

Spencer Rathbun


2 Answers

There must be at least one statement in a block. A lone string literal is considered a valid statement, even if it is being used as the docstring. It should not cause any memory leaks though, since the compiler omits it in the actual code.

like image 51
Ignacio Vazquez-Abrams Avatar answered Dec 06 '25 10:12

Ignacio Vazquez-Abrams


Python's syntax is explained in the language reference. The relevant parts are:

7.7 Function definitions

...
funcdef        ::=  "def" funcname "(" [parameter_list] ")" ":" suite
...

So, the syntax for a function is all that stuff up to the colon, followed by a suite.

7. Compound statements

...
suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
...
stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]
...

So a suite can be either a stmt_list or an indented block containing at least one statement... And a stmt_list is just a bunch of simple_stmt chunks connected by semicolons on one line.

Finally:

6. Simple statements

simple_stmt ::=  expression_stmt
             | assert_stmt
             ...

That shows that a simple_statement can be any expression, or an assert or whatever else was on the list.

You can click the links on those pages to explore further. An expression_stmt is just any expression evaluated by itself, like:

dir
2
"cat"
int()

Which is a perfectly valid python program that will parse and run, even though it does nothing.

A function's docstring is also an expression. It's just a string that happens to be treated specially by the system.

The special treatment isn't part of the syntax, though. It happens in another phase, long after the parser has built its abstract syntax tree.

I would look elsewhere for the memory issue... :)

like image 44
tangentstorm Avatar answered Dec 06 '25 10:12

tangentstorm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!