Saturday, December 19, 2015
Python doesn't know the meaning of life :-)
Attribution of above image
I was checking out the repr() and __repr__() functions / methods of Python (in the process of creating an exercise for one of my students), when I came across this interesting 'feature' of Python:
I did this at the Python interpreter prompt (in both 2.7 and 3.4):
>>> ''.__repr__() # Call the dunder repr method on an empty string.
"''"
>>>
(Got the expected output - the representation of the empty string.)
Similarly for a list, a tuple, etc.:
>>> [].__repr__()
'[]'
>>> ().__repr__()
'()'
But when I did this:
>>> 42.__repr__()
I got this:
File "<stdin>", line 1
42.__repr__()
^
SyntaxError: invalid syntax
So, it looks like Python does not know the meaning of life :-)
Jokes apart, I also tried this (actually, before trying 42):
>>> 1.0.__repr__()
'1.0'
which worked. And the only difference between the example above that worked (1.0), and the two that did not (1 or 42), is that the latter two use an int, and the former uses a number with a decimal point.
But both also use the dot as the attribute access operator, which leads me to think that this is the reason for the issue (for ints): there is an ambiguity between interpreting 1.something as 1.other_decimal_digits (making it a floating point number) and as 1.some_attribute (making it an attribute access on an object) (because 1, like (almost) everything in Python, is an object (of type int), as can be seen by doing:
>>> dir(1)
and
>>> type(1)
Interested to know if anyone has a better explanation of this, and also of whether the same issue/anomaly, if it is one, occurs in any other languages, or if not, why not.
- Vasudev Ram - Online Python training and programming Signup to hear about new products and services I create. Posts about Python Posts about xtopdf My ActiveState recipes
Wednesday, September 30, 2015
Find the caller and caller's caller of a Python function
While browsing some Python posts on the Net, I saw one that made use of the sys._getframe() function. I had seen that function before, and remembered that it returns information about currently active stack frames. So I looked up the docs for sys._getframe(), thinking that it might be possible to use it within a function, to find that function's caller. Turned out that it could. I also googled for terms like "find the name of the calling function in python", and found two relevant Stack Overflow (SO) posts:
Getting the caller function name inside another function in Python?
Python: How to get the caller's method name in the called method?
It can be done by using either inspect.stack() or sys._getframe(). (The inspect module in Python's standard library supports that (finding a function's caller via stack frames), as well as some other useful introspection techniques.)
(I had blogged a couple of times about inspect, earlier, here:
Python's inspect module is powerful
and here:
Using inspect.getargvalues to debug Python programs
)
So I tried out the SO code examples and slightly modified them to make these two small programs that print the name of the caller, and the caller's caller.
Here is the first program:
''' File: find_callers.py Run with: python find_callers.py ''' import sys def foo(): print "I am foo, calling bar:" bar() def bar(): print "I am bar, calling baz:" baz() def baz(): print "I am baz:" caller = sys._getframe(1).f_code.co_name callers_caller = sys._getframe(2).f_code.co_name print "I was called from", caller print caller, "was called from", callers_caller foo()When run, this program outputs:
I am foo, calling bar: I am bar, calling baz: I am baz: I was called from bar bar was called from foo
The second program is similar to the one above, except that, just for fun and to do it differently, I defined part of the overall code expression as a string, interpolated the argument (2 or 3) into it using Python string formatting, and then eval()'ed the resulting string. Note that since there is now an additional function call (eval), I had to change the arguments to sys._getframe() from 1 and 2 to 2 and 3:
# File: find_callers_with_eval.py # Run with: python find_callers_with_eval.py import sys getframe_expr = 'sys._getframe({}).f_code.co_name' def foo(): print "I am foo, calling bar:" bar() def bar(): print "I am bar, calling baz:" baz() def baz(): print "I am baz:" caller = eval(getframe_expr.format(2)) callers_caller = eval(getframe_expr.format(3)) print "I was called from", caller print caller, "was called from", callers_caller foo()The output of this second program was identical to the first.
Note that the Python documentation says:
[ CPython implementation detail: This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python. ]
Also, use eval() with care, and only on trusted code.
- Vasudev Ram - Online Python training and programming Dancing Bison EnterprisesSignup to hear about new products and services that I create. Posts about Python Posts about xtopdf
Thursday, September 15, 2011
Python stdlib docs as Vim help files
Saw this recently.
The Python standard library documentation as Vim help files:
It seems to be a work in progress but may be of use. The potential benefit is that you can look up Python library documentation from within Vim by typing ":help py2stdlib". Neat idea.
It is by Jeet Sukumaran ( http://jeetworks.org/about ) , currently a PhD student at the University of Kansas, who uses Python for his work.
Posted via email
- Vasudev Ram @ Dancing Bison
Wednesday, September 7, 2011
Some ways of doing UNIX-style pipes in Python
For a project I'm working on, I was recently thinking about how to implement something similar to UNIX-style pipes in Python; not necessarily exactly the same, but conceptually similar.
I had deliberately decided *not* to search for this on the Net, so that I could first think about it myself, and figure something out.
But coincidentally today, while browsing the Usenet group comp.lang,python, I came across this post mentioning issues with doing one-liners in Python.
One of the answers given was to check out PyP, a tool for Python that lets you do pipes (in a sense) and data munging like the powerful UNIX tools sed and awk. PyP stands for "Python Power at the Prompt, meaning the UNIX shell prompt, of course. It has an interesting and unusual approach. It is open source, hosted on Google Code, and was apparently initially created by a division of Sony Pictures called ImageWorks, "to facilitate the construction of complex image manipulation unix commands during visual effects work on Alice in Wonderland, Green Lantern, and the upcoming The Amazing Spiderman". Good performance was mentioned as one of it's plus points, apart from the pipe facility itself.
So I checked PyP out a bit and it seems like a nice tool. It has a fairly intuitive syntax for at least basic operations, and is also extensible in at least couple or so ways for more advanced users
I also did a Google query or two with appropriate keywords to find other such tools. Here are some of them, including PyP again:
PyP: http://code.google.com/p/pyp
Pipe module for Python by Julien Palard:
http://dev-tricks.net/pipe-infix-syntax-for-python
Piping support in the standard Python library:
http://docs.python.org/library/pipes.html
Will update this post later after checking these tools out some more.
Posted via email
- Vasudev Ram @ Dancing Bison
Sunday, July 3, 2011
Book: The Python Standard Library By Example, by Doug Hellmann
Just got to know about this new Python book published by Addison-Wesley Professional:
The Python Standard Library By Example: by Doug Hellmann:
http://www.doughellmann.com/books/byexample/index.html
Excerpt about the book:
[ The Python Standard Library contains hundreds of modules that provide tools for interacting with the operating system, interpreter, and Internet—all of them tested and ready to be used to jump-start the development of your applications. This book presents examples demonstrating how to use the most commonly used features of the modules that give Python its "batteries included" slogan, taken from the popular Python Module of the Week (PyMOTW) blog series. ]
Doug Hellmann is a veteran Pythonista and the Communications Director of the Python Software Foundation, and is also heavily involved in Python in many other ways. I've read many of his blog posts from the PyMOTW series, and they are good.
The above web page has:
- a description of the book, and who the target audience is - the intermediate Python programmer - but even if you are a newbie Python programmer but experienced in other language(s), you can probably derive a lot of value from both the blog series and the book
- a link to a free PDF containing the table of contents, foreword, introduction, index, and chapter 2 ("Data Structures") from the final version of the manuscript
- a link to a free e-book containing the table of contents, foreword, introduction, index, and chapter 1 ("Text"), available through the iTunes book store
Posted via email
- Vasudev Ram - dancingbison.com