Unable to comment out code involving multiline strings - python

Basically I am curious about why this throws a syntax error and what is the pythonic way to 'comment out' portions of my code that I am not using, for example during a debugging session.
'''
def foo():
'''does nothing'''
'''

You can use triple double quotes to comment out triple single quotes:
"""
def foo():
'''does nothing'''
"""

Python is interpreting your code like this:
First comment:
'''
def foo():
'''
Second comment:
'''
'''
Therefore, the "does nothing" is outside the comment, and python tries to interpret it, but the syntax is invalid, so it gives an error.

The Pythonic way is to understand the difference between a multi-line string and a comment and use them appropriately.
Python does not have multi-line comments, but many python aware editors and IDE's have ways to automatically comment out selected multiple lines, (and the reverse). You might want to search for that useful functionality.

Related

Vim highlighting with python recursive definitions

I use the jellybeans colorscheme for vim. I'm noticing that when writing a recursive function that the name is only highlighted at the beginning of the definition and not within the indentation block:
def fact(n): #'fact' appears yellow
...
return n*fact(n-1) #'fact' appears in white like regular text, variables etc.
Is there a way to fix this?
Yes there are solutions but do you really want that: it can highlight just all your code.
Just highlight all what looks like myfunc():
:syn match calledFunc /\(\w\|\.\)\+\ze(/
:hi calledFunc ctermfg=Yellow
Note:
With the syntax priority (:help syn-priority) this should do exactely what you want. Because functions definitions like def myfunc(): are considered as keyword (and have higher priority):
see /usr/share/vim/vim74/syntax/python.vim:
syn keyword pythonStatement class def nextgroup=pythonFunction skipwhite
syn match pythonFunction "\%(\%(def\s\|class\s\|#\)\s*\)\#<=\h\%(\w\|\.\)*" contained
HiLink pythonFunction Function
an other slow solution can be:
1/ Parse the file (and included ?) to get all functions, store them in a list
2/ Hightlight these functions

When is Python code between """ """ executed? [duplicate]

Let's say, I've got a function like this:
def myFunc():
# useful function to calculate stuff
This will produce an indentation error, unless I add pass:
def myFunc():
# useful function to calculate stuff
pass
However, if I replace a comment with docstring, no pass is necessary:
def myFunc():
"""useful function to calculate stuff"""
This seems like an odd feature as neither of these are used in the program, as far as I know. So, why does it behave like this?
A comment is outright ignored by the interpreter, so omitting a block after an indent is a syntax error. However, a docstring is a real Python object--at its most basic, a literal str. A lone expression is a valid block of code:
'This is a string. It is a valid (though pretty useless) line of Python code.'
In the case of docstrings in particular, there's also some additional functionality going on, such as being used to set the __doc__ attribute.
>>> def myFunc():
... '''MyDocString'''
...
>>> print(myFunc.__doc__)
MyDocString
Note that this also works for classes:
>>> class MyClass(object):
... '''MyClassDocString'''
...
>>> print(MyClass.__doc__)
MyClassDocString
A docstring isn't just a comment. It actually has meaning to the interpreter. In the case with a docstring, you could do myFunc.__doc__ and actually get your docstring back (In the other case with a pass, the result myFunc.__doc__ would be None).
In other words, you are actually adding some code to the function body to modify it's behavior (in some circumstances), so no pass is necessary.

Appending tabs to all print statements in Python

I'm writing a Python console application, and I would like its output to be tabbed one tab over to set it apart from the command line.
Is there a single-command way to have tabs in front of all print statements without having to type each one explicitly?
Thank you!
There isn't any setting in Python to be able to do that, the easiest way would be to create a new function like so.
def printTab(*args):
args = ("\t",)+args
print(*args)
Comment on other answers:
If you let your new function take a single argument, rather than multiple arguments (using *args, you lose a lot of the functionality in the Python 3 print function.
What you'll want to do is just create an alternate print command for this specific use. It might look something like this:
from __future__ import print_function
def print_tabbed(str_to_print):
print('\t{}'.format(str_to_print))
While there may be a way to do what you ask (see this link if that's really what you want), I think it's a bad idea and you could improve a bit on this solution.
If you define a function like this :
def printWithTab("text"):
print("\t{}").format(text)
You could use this function instead.
>>>print(test)
test
>>> printWithTab("test")
test
(assuming python 3+)

Commented block indentation in python

Is there a way to avoid "expected indent block" errors in Python without adding pass to a function?
def exclamation(s):
# s += "!!!"
# return s
print exclamation("The indented horror")
The above code results in an error on line 5. Yes, remove the comments and the code works fine. However, in debugging stuff I often find myself in a similar situation. Is this just a hang-up of the off-side rule and something I need to get used to or are there ways around this?
There has to be something within your function definition to avoid a SyntaxError.
The issue is that the interpreter will effectively ignore comments during parsing, and so while to a human it might look like something is there, to the parser it is empty.
As jonrsharpe has pointed out in a comment, you can use docstrings to "comment out" your code and have it still work. This is because the docstring is, in effect, a normal string. As such this will be parsed and won't cause a SyntaxError. To take your example code it would look like:
def exclamation(s):
'''s += "!!!"
return s'''
# This should print None as nothing is now returned from the func
print(exclamation("The indented horror"))

Why can't I "string".print()?

My understanding of the print() in both Python and Ruby (and other languages) is that it is a method on a string (or other types). Because it is so commonly used the syntax:
print "hi"
works.
So why doesn't "hi".print() in Python or "hi".print in Ruby work?
When you do something like "hi".print(), you are implying that the string object "hi" has a method print. This is not the case. Instead, print is a function that takes a string (or other types) as input.
Ruby does have a method Object#display (doc here), which sends a representation of the object to the current output stream, or one specified as an argument.
(I find that it's hard to work with in irb if I use ; at the end of a line to suppress the printing of the return value; if I do that, display's output isn't shown, even if I flush the stream.)
It's not a method on a string. Prior to Python 3, it was a statement (just like break or import), and you could use both print "hi" and print("hi"). From Python 3, it was replaced by a function, thus you can no longer use print "hi":
Print Is A Function
The print statement has been replaced with a
print() function, with keyword arguments to replace most of the
special syntax of the old print statement (PEP 3105).
Why should it work? String classes rarely have void print methods - and you would never need them, because the standard static print function can print those strings anyway. It is important to note: method(someObject) is not necessarily the same as someObject.method().
What do you propose str.print should do?
print to stdout? how about stderr? or a file? or a serial port?
Printing to stdout is really a special case but it's so ubiquitous that sometimes it can be overlooked.
Then we'd have to specify where str should print to every time we create a string?
At the very least we'd have to say
"foo".print(sys.stdout)
Hopefully that looks awful to you too. It's a confusion of responsibilities
print isn't a method on a string in Python (or in Ruby, I believe). It's a statement (in Python 3 it's a global function). Why? For one, not everything you can print is a string. How about print 2?
In case you are more happy to use a method rather than a statement in Ruby you can use the method display ("test".display) to achieve this or define a new method easily like
class String
def print
puts self
end
end
and use it like this
"test".print

Categories