Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I stumbled upon an interesting and unexpected feature of Python:
def fun():
"""Foo’s docstring"""
is a valid function? According to PEP 257, “A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition” meaning that the docstring itself is considered a statement?
I would have expected that at least a pass statement is required here. The above example contradicts the Python Zen of “explicit is better than implicit” as pass states an explicit intent, and a docstring does not.
Can anybody shed some light on the intent?
A string literal is just like any other literal. It also works if you just put in an integer:
def func():
1
However, it doesn't work if you only use a comment:
def func():
# test
# IndentationError: expected an indented block
Even though it's also added as docstring (saved in the __doc__ attribute) it's also a function level constant:
def func():
"""I'm a function"""
>>> func.__code__.co_consts
("I'm a function", None)
So the presence of a string literal as only content of a function doesn't change how the function is actually "parsed" and "compiled" itself. Well, apart from the fact that it also got a not-None __doc__ attribute.
It's actually very handy for abstractmethods (see for example "Body of abstract method in Python"), where you don't need an actual function body.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am very curious about the classes that exist in the module builtins that are not accessible directly. Such as
type(lambda: 0) # __name__='function' of __module__='builtins'
type((lambda: 0).__code__) # __name__='code' (aka. bytecode) of __module__='builtins'
None.__class__ # __name__='NoneType' of __module__='builtins'
And the matriarch:
str.__mro__[1] # # __name__='object' of `__module__` 'builtins'
traceback as passed to the __exit__ magic method of a context manager is the same:
def __exit__(self, exc_type: Exception, exc_value: str, exc_traceback: 'bultins.traceback'):
pass
(The module traceback is a module and simply shares the name, ditto for tracemalloc.Traceback). In the above the object name is a string, but this is a rare example of a "hidden" builtins class and typehinting because for a function instances typing.Callable does the job.
Q: what is the name for these "hidden" builtin classes?
I understand that the builtins are written in C in CPython. I had a quick gander at the CPython Github repo and I could not figure out why unlike tuple they are "hidden". I use the word "classes" as they have the same magic methods etc. and work like other classes:
NoneType() == None # True as expected
bytecode = code(...) # bytecode...
fxn = function(bytecode)
Q: Is there a PEP reason why they are not in builtins?
If it is simply to stop namespace pollution, I'd have though they'd be underscored objects in the builtin module say or in some module... unless they are somewhere else
Q: Can they be imported directly by somewhere else?!
Maybe as an answer to reasoning – afaik, this is about not providing public API that goes agains semantics.
I.e. instantiating NoneType is something that you rather should not do, same as doing equality comparison for None.
If you have specific needs to build something dynamically – please provide them, usually there's an official API to do so (ast, as an example)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to know the assigning to variable more specifically. My code:
def fun():
return 5
var=fun()
print(var)
var=fun
print(var)
Is there any difference in the both or are they the same? I use Python 3.
var = fun() calls the function fun. The returned value (in this case, 5) is then assigned to var.
var = fun assigns the function fun refers to, to var. You can now call the function by doing either fun() or var(). Two different names for the same function.
This is what people mean when they say python has 'first-class functions' - they can be treated like any other variable, as opposed to the special treatment they get in languages like Java.
Adding the parenthesis fun() would call/run the function, and return 5, whereas if you don't add the parenthesis fun, it wouldn't run the function, it would just give:
<function fun at 0x000000D4B44E8730>
Whereas with the parenthesis, it would give:
5
Without calling the function (without using the parenthesis) would just give a function reference, and wouldn't run the function. Whereas if you add the parenthesis it would.
Here is an example:
def fun():
return 'The function is called!'
print(fun())
print(fun)
Output:
The function is called!
<function fun at 0x0000001615DD7730>
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
For example in Python 3: print("Hello world")
And in Python 2: print "Hello world"
This makes me want to use Python 2 instead of Python 3, because it's simpler.
From http://www.python.org/dev/peps/pep-3105/
The following arguments for a print() function are distilled from a
python-3000 message by Guido himself:
print is the only application-level functionality that has a statement dedicated to it. Within Python's world, syntax is generally
used as a last resort, when something can't be done without help from
the compiler. Print doesn't qualify for such an exception.
At some point in application development one quite often feels the need to replace print output by something more sophisticated, like
logging calls or calls into some other I/O library. With a print()
function, this is a straightforward string replacement, today it is a
mess adding all those parentheses and possibly converting >>stream
style syntax.
Having special syntax for print puts up a much larger barrier for evolution, e.g. a hypothetical new printf() function is not too far
fetched when it will coexist with a print() function.
There's no easy way to convert print statements into another call if one needs a different separator, not spaces, or none at all. Also,
there's no easy way at all to conveniently print objects with some
other separator than a space.
If print() is a function, it would be much easier to replace it within one module (just def print(*args):...) or even throughout a
program (e.g. by putting a different function in builtin.print).
As it is, one can do this by writing a class with a write() method and
assigning that to sys.stdout -- that's not bad, but definitely a much
larger conceptual leap, and it works at a different level than print.
In Python2, print is a statement but in Python3, print is a function
Try this
print(print("Welcome"))
in python 2, it will produce SyntaxError: invalid syntax but in python3 it will produce
Welcome
None
It means that, first the inner print is invoked which prints Welcome and it returns None to the outer print which simply prints it.
Short simple answer: print was made a function in Python 3 as #kojiro suggested.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
def f():
return True
print(f())
or
def f():
return True
if f():
print('True')
else:
print('False')
Should I round it in if statement or simply print out the value, in Python 3.3.2?
print automatically converts input to its string representation. So, the two methods actually do the exact same thing. Considering that, why not use the first? It is a lot cleaner.
Also, the second method can really be simplified:
print('True' if f() else 'False')
Having that much code for something so simple isn't necessary.
If your function always returns a bool, then just print it, like this:
print(f())
If you need to convert it to a string without printing it, use str(f()) or repr(f()). For the bool type these two are equivalent, but e.g. if their argument is an str, they are different: repr(str_obj) returns it properly quoted and escaped.
If it's not always a bool, but you want to print something depending on its truth value, then use an if, like in your question or in iCodez' answer. Alternatively, you can convert it to a bool, and then print it:
print(bool(f()))
Personally, the:
print(f())
form looks nicer. However, one thing to consider is that you have baked in a call to print what is essentially debugging output with the call that is causing the functionality to be invoked. This would make it painful later when you want to turn off all the annoying print statements when you are ready to build upon your program.
You could instead have a function such as:
LOGGING_ENABLED = True
def print_if(my_bool):
if LOGGING_ENABLED:
print str(my_bool)
This will ensure that the function is always invoked but the debug output happens only if you want it.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
class MyClass(object):
def fn():
return 1
for i in [method for method in dir(inspect) if callable(getattr(inspect, method))]:
print i(MyClass) // Error here
Error: TypeError: 'str' object is not callable
If i change print statement to:
print "%s(MyClass)" % i
this simply print:
ArgInfo(MyClass)
and so on...
dir(module) returns a list of names (strings) defined in the module, not the actual functions or values. To get those, use getattr, which you already use for the callable check.
for name in dir(your_module):
might_be_function = getattr(your_module, name)
if callable(might_be_function):
print might_be_function(your_parameters)
Of course, it might still be the case that the function is not applicable to the given parameters, so you might want to check this first, or wrap in in a try block.
Do you need to call all methods by name like that?
class C1:
def f1(self):
print('f1---')
def f2(self):
print('f2---')
inspect = C1()
for i in [method for method in dir(inspect) if callable(getattr(inspect, method))]:
getattr(inspect, i)()