Question

So I understand that if I do the following

print """ Anything I 
          type in here 
          works. Multiple LINES woohoo!"""

But what if following is my python script

""" This is my python Script. Just this much """

What does the above thing do? Is it taken as comment? Why is it not a syntax error?

Similarly, if I do

"This is my Python Script. Just this. Even with single quotes."

How are the above two scripts interpreted?

Thanks

Was it helpful?

Solution

The triple quotes ''' or """ are just different ways of representing strings. The advantage of triple quotes is that it can span multiple lines and sometimes serve as docstrings.

The reason:

"hadfasdfas"

doesn't raise any error is because python simply creates the string and then doesn't assign it to anything. For the python interpreter, it is perfectly fine if you have a pointless statement in your code as long as there are no syntax or semantics errors

Hope that helps.

OTHER TIPS

The string is just evaluated, and the interpreter noticing it wasn't assigned to anything, throws it away.

But in some special places, this string is actually assigned to the __doc__ property of the item:

def func(arg):
  """
  Does stuff. This string will be evaluated and assigned to func.__doc__.
  """
  pass

class Test:
  """
  Same for Test.__doc__
  """
  pass

At the top of module.py:

"""
module does stuff. this will be assigned to module.__doc__
"""
def func():
...

In addition to @sshashank124 answer I have to add that triple quoted strings are also used in testing https://docs.python.org/2/library/doctest.html

So consider this code snippet:

def some_function(x, y):
"""This function should simply return sum of arguments.
It should throw an error if you pass string as argument

>>> some_function(5, 4)
9
>>> some_function(-5, 4)
-1
>>> some_function("abc", 4)
Traceback (most recent call last):
    ...
ValueError: arguments must numbers
"""
if type(x, str) or type(y, str):
    raise ValueError("arguments must numbers")
else:
    return x + y

if __name__ == "__main__":
    import doctest
    doctest.testmod()

If you import this tiny module, you'll get the some_function function.
But if you invoke this script directly from shell, tests given in the triple quoted string will be evaluated and the report will be printed to the output.

So triple quoted strings can be treated as values of type string, as comment, as docstrings and as containers for unittests.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top