EntropySink

Technical & Scientific => Programming => Topic started by: JaWiB on February 15, 2012, 07:11:56 PM

Title: Anyone use Python?
Post by: JaWiB on February 15, 2012, 07:11:56 PM
The guys in my lab like to use python for a lot of the projects we do, so I thought I'd give it a whirl. Some of the packages are pretty handy and easy to use, so it seems like a decent choice. Problem* is, they don't write OO code and I'd much rather use classes for a lot of the stuff we're doing. For instance, we use Python code to control various instruments some of which use GPIB for communication and some of which use other methods, like RS232. So I would envision, for example, having a generic class for a temperature controller which would have methods like GetTemp and SetTemp.

In C++, I'd probably define some sort of abstract base class and then code specific classes inheriting from it for each model of temperature controller we use (we do in fact have at least one that uses serial and one that uses GPIB). But in Python, I've just learned, you have "Duck Typing" which seems to be an alternative to using inheritance. My personal opinion is that it seems like sloppy coding, but is it really just common practice to use duck typing?

*It's actually not really a problem since all of our coding projects are small and we could get away with a lot of bad practices, but I like to do things right :D
Title: Re: Anyone use Python?
Post by: Mike on February 15, 2012, 07:40:58 PM
I don't but I keep meaning to get competent.  I still maintain that using indention for block level control is just fucking stupid.
Title: Re: Anyone use Python?
Post by: JaWiB on February 15, 2012, 07:58:04 PM
Yeah, I miss my curly braces. And semicolons.
Title: Re: Anyone use Python?
Post by: Perspective on February 15, 2012, 08:52:59 PM
I use python a lot. Mostly for small things though, basically any time I need to process text. It's really handy for manipulating and transforming strings.

For any larger data intensive things I use Java.
Title: Re: Anyone use Python?
Post by: -KEN- on February 16, 2012, 02:10:32 AM
I use Python all day.

Duck typing won't stop you from creating base classes. That would be awful.

Code: [Select]
class BaseTempController(object):
    """
    Base class for temperature controllers
    """
    def __init__(self, temp=None):
        self._temp = temp

    def get_temp(self):
        return self._temp

    def set_temp(self, temp):
        self._temp = temp

class TempControllerA(BaseTempController):
    """
    For whatever reason, TempControllerA is evil and always
    reports the temperature 3 degrees colder than it really is.
    """
    def get_temp(self):
        """
        Lie to the people.
        """
        return self._temp - 3
   

If you want to be fancy, you can make get_temp() a property called temp, and then you could just do controller.temp instead of get_temp():

Code: [Select]
...snip...
    @property
    def temp(self):
        return self._temp - 3
...
controller = TempControllerA(45)
controller.temp    #temp is a read-only property now.
Title: Re: Anyone use Python?
Post by: ober on February 16, 2012, 09:08:11 AM
That looks fucking awful.  I'll stick to PHP and Java.
Title: Re: Anyone use Python?
Post by: micah on February 16, 2012, 09:15:15 AM
The guys in my lab like to use python... Problem is, they don't write OO code and I'd much rather use classes for a lot of the stuff we're doing.

Do they work in other OO languages, 'cuz perhaps they just don't understand it enough to get the benefits.  Coming from an inline PHP background I was really resistant to OOP a few years ago... I'm sure there are plenty of threads on here even about me whining about it.  In the end, I found myself in a immersive OOP environment and was forced to just learn it.  It didn't take long for the concept to finally click.  Now I can't imaging working without it.

Also,

(http://imgs.xkcd.com/comics/python.png)
Title: Re: Anyone use Python?
Post by: -KEN- on February 16, 2012, 12:01:03 PM
That looks fucking awful.  I'll stick to PHP and Java.

Python is so much more readable and sane than PHP. I think objectively at this point. Stockholm Syndrome.

I guess PHP classes aren't the most awful thing I've ever seen, but I wouldn't call them pretty -- http://www.php.net/manual/en/language.oop5.basic.php
Title: Re: Anyone use Python?
Post by: JaWiB on February 16, 2012, 12:51:46 PM
If you want to be fancy, you can make get_temp() a property called temp, and then you could just do controller.temp instead of get_temp():
Sweet, didn't know about properties.

Do they work in other OO languages, 'cuz perhaps they just don't understand it enough to get the benefits.  Coming from an inline PHP background I was really resistant to OOP a few years ago... I'm sure there are plenty of threads on here even about me whining about it.  In the end, I found myself in a immersive OOP environment and was forced to just learn it.  It didn't take long for the concept to finally click.  Now I can't imaging working without it.
I don't really know. Probably not. Some of the ancient code in the lab was written in C++ and they used classes, but I don't think the guys who are here now wrote any of it. And even that code was sort of procedural code with classes
Title: Re: Anyone use Python?
Post by: -KEN- on February 16, 2012, 12:53:22 PM
I should note you could write everything more succinctly this way (this is from an interactive REPL session, hence the dots and >>).

Code: [Select]
>>> class BaseTempController:
...   def __init__(self, temp=None):
...     self.temp = temp
...
>>> a = BaseTempController(45)
>>> a.temp
45
>>> class TempControllerOfLies(BaseTempController):
...   def get_temp(self):
...     return self.temp - 3
...
>>> a = TempControllerOfLies(45)
>>> a.get_temp()
42

But given what JaWiB was trying to do, I went for verbosity in the base class, and made the temp variable private.

Title: Re: Anyone use Python?
Post by: Mike on February 16, 2012, 12:58:46 PM
-Ken- do you know of any good python libraries that let me make some simple GUIs?  Need to expand some command line tools to do some file selection and such.  Mainly checkboxes, radio lists, and buttons.
Title: Re: Anyone use Python?
Post by: -KEN- on February 16, 2012, 12:59:00 PM
Sweet, didn't know about properties.

Yeah, I'm not a huge fan of getters and setters in my private code, but if you're writing an API or a library, it's useful to let people think they're just accessing the variable directly. Pretty useful for things like this too:

Code: [Select]
class Person:
  def __init__(self, first_name, last_name):
    self.first_name = first_name
    self.last_name = last_name

  @property
  def name(self):
    return "%s %s" % (self.first_name, self.last_name)

That way you can:

me = Person("Joe", "Schmoe")
print me.name #"Joe Schmoe"
Title: Re: Anyone use Python?
Post by: JaWiB on February 16, 2012, 01:42:10 PM
I find it funny how Python makes you use self.variable_name. It's like having to write this->variable_name all the time, which would make people laugh at you in C++
Title: Re: Anyone use Python?
Post by: -KEN- on February 16, 2012, 01:42:32 PM
-Ken- do you know of any good python libraries that let me make some simple GUIs?  Need to expand some command line tools to do some file selection and such.  Mainly checkboxes, radio lists, and buttons.

I toyed with the wx library once upon a time, but I'm not qualified to make a recommendation one way or the other. Unless I'm toying around on the iPhone, I either write CLI or HTML. Not to sound too trendy, but TileMill is written in Node and HTML, and I would bet most people think it's a native application. http://mapbox.com/tilemill/

Perhaps you could just write a simple, self-contained HTML-based frontend.
Title: Re: Anyone use Python?
Post by: -KEN- on February 16, 2012, 01:43:46 PM
I find it funny how Python makes you use self.variable_name. It's like having to write this->variable_name all the time, which would make people laugh at you in C++

Yeah, it is definitely annoying. Much has been written about 'self' in Python (both for and against, but mostly against I would imagine), but in the end it's really only a minor annoyance.
Title: Re: Anyone use Python?
Post by: Mike on February 16, 2012, 01:50:44 PM
-Ken- do you know of any good python libraries that let me make some simple GUIs?  Need to expand some command line tools to do some file selection and such.  Mainly checkboxes, radio lists, and buttons.

I toyed with the wx library once upon a time, but I'm not qualified to make a recommendation one way or the other. Unless I'm toying around on the iPhone, I either write CLI or HTML. Not to sound too trendy, but TileMill is written in Node and HTML, and I would bet most people think it's a native application. http://mapbox.com/tilemill/

Perhaps you could just write a simple, self-contained HTML-based frontend.
Thanks, I'll take a look.  I need the program to run as a particular linux/mac user so using a webserver is out (we tried).  Part of what we are doing is doing svn commands so file ownership becomes a big pain.
Title: Re: Anyone use Python?
Post by: -KEN- on February 16, 2012, 02:13:27 PM
Thanks, I'll take a look.  I need the program to run as a particular linux/mac user so using a webserver is out (we tried).  Part of what we are doing is doing svn commands so file ownership becomes a big pain.


Node can run as its own self-contained web server (the TileMill code is open source and on Github); python can actually do the same. We frequently create quick Django apps for data entry around here. It's nice, because anyone in the VPN can access it via the IP, and updates made to the server are instant for everyone.

If you created a quick django app, you would just need to run `python manage.py runserver 0.0.0.0:8000` from that user account, and anyone accessing the IP will make changes owned by the account you ran the command from.

Django is a huge framework though. You could check out Flask - http://flask.pocoo.org/. Very stripped down and much easier to write a small app in. You'd basically just write a route that showed the control panel at a URL (like '/'), and another one that accepts GET or POST input from the form and figures out what commands to execute locally.
Title: Re: Anyone use Python?
Post by: JaWiB on February 16, 2012, 02:13:56 PM
I was reading about properties and the guy wrote this:
Code: [Select]
@Property
    def name():
        doc = "The person's name"
#...
What's the deal with the doc= line? I thought you were supposed to use triple quotes for docstrings: """The person's name"""
Title: Re: Anyone use Python?
Post by: Mike on February 16, 2012, 02:15:22 PM
Thanks -Ken-.  Hopefully, once I get these current projects done I'll have more time to check that out.
Title: Re: Anyone use Python?
Post by: -KEN- on February 16, 2012, 02:21:52 PM
I was reading about properties and the guy wrote this:
Code: [Select]
@Property
    def name():
        doc = "The person's name"
#...
What's the deal with the doc= line? I thought you were supposed to use triple quotes for docstrings: """The person's name"""

If he's using that and a capital P on @property, I wouldn't recommend listening to him. I've never seen that before; and furthermore, doc is represented by __doc__, not 'doc', so I don't think that even works.
Title: Re: Anyone use Python?
Post by: JaWiB on February 16, 2012, 02:22:48 PM
Here's the blog article: http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/
Title: Re: Anyone use Python?
Post by: -KEN- on February 16, 2012, 02:25:11 PM
Yeah, that just plain doesn't work.

Code: [Select]
>>> def stuff():
...   doc="junk"
...
>>> stuff.__doc__
>>> def stuff():
...   __doc__ = "junk"
...
>>> stuff.__doc__
>>> def stuff():
...   print "OK"
...
>>> stuff.__doc__ = "This prints 'OK'"
>>> stuff.__doc__
"This prints 'OK'"
>>> def junk():
...   """
...    this does nothing.
...   """
...   pass
...
>>> junk.__doc__
'\n   this does nothing.\n  '
Title: Re: Anyone use Python?
Post by: Perspective on February 16, 2012, 08:17:42 PM
I was reading about properties and the guy wrote this:
Code: [Select]
@Property
    def name():
        doc = "The person's name"
#...
What's the deal with the doc= line? I thought you were supposed to use triple quotes for docstrings: """The person's name"""

Triple quotes are just for multi-line strings in general. You can use them anywhere, not just for the __doc__ string.
Title: Re: Anyone use Python?
Post by: -KEN- on February 17, 2012, 06:42:59 PM
Yeah, but you can't just write doc="string" inside of a function. You're just creating a local variable; it has nothing to do with __doc__
Title: Re: Anyone use Python?
Post by: JaWiB on February 27, 2012, 02:41:44 PM
Either of you guys use eclipse? Is there a way to debug using the interactive console?
Title: Re: Anyone use Python?
Post by: micah on February 27, 2012, 02:58:27 PM
I've tried using elcipse a couple times in the past. Before, as an alternative to dreamweaver because I just wanted a free IDE with sytax highlighting, and most recently because all of the phonegap tutorials basically force you to use it.*  In both instances I've become fairly frustrated with the UI and the processess for setting up the coding environment on each project. In otherwords, I have no idea how to debug with it, sorry :)


*of course, now that adobe has bought phonegap, its integrated into Dreamweaver CS 5.5+ so I guess that the deal breaker to keep me on their platform.

Title: Re: Anyone use Python?
Post by: ober on February 27, 2012, 03:31:05 PM
We use Eclipse where I work.  But that's for Java.  And the debug view is fucking amazing.  I really like Eclipse for what I do at work but I think it's too much bloat for some of my personal projects.
Title: Re: Anyone use Python?
Post by: JaWiB on February 27, 2012, 04:52:07 PM
I've come to like eclipse since I can use it for basically any language I want. The debugger works fine, but I'd like to take advantage of the fact that I can run any function without compiling anything and be able to step through whatever I call using the debugger. The easiest way I've found is just to write a little debug python script and then hit Run->Debug with that file open. Seems fine  :dunno:

Now I'm wondering how to write code that only executes in debug mode, like I'd do in C++:
Code: [Select]
#ifdef DEBUG
//...
#endif
Not sure that even makes sense though since it isn't compiled. Basically I want to be able to switch on and off communication with the hardware so I can test the rest of the code before trying to actually control the instrumentation.
Title: Re: Anyone use Python?
Post by: JaWiB on February 27, 2012, 05:39:42 PM
While I'm at it, what are your conventions for naming files and classes? I'm finding it cumbersome to name a file "ls331.py" and have a class named "LS331" now I have:
Code: [Select]
from instruments import ls331
#...
ls331.LS331.foo()
I could use "import ls331 as tc" or something but then what do I call the instances of the class?
Title: Re: Anyone use Python?
Post by: Perspective on February 27, 2012, 09:40:58 PM
you can also use "from ls331 import LS331"
Title: Re: Anyone use Python?
Post by: JaWiB on February 27, 2012, 09:49:50 PM
Oh, nice, thanks!
Title: Re: Anyone use Python?
Post by: -KEN- on February 28, 2012, 01:53:33 AM
You may be tempted to start writing

from ls331 import *

This is generally frowned about. Python people have a hard-on for explicit imports.
Title: Re: Anyone use Python?
Post by: -KEN- on February 28, 2012, 01:56:49 AM
Re: debugging, you can use this -- http://docs.python.org/library/pdb.html

I'm more a traceback-and-tinker sort of debugger ;)
Title: Re: Anyone use Python?
Post by: hans on May 13, 2012, 11:42:38 PM
I just started playing with Python again and I'm enjoying it for the most part. I'm using the Flask framework and I think Python is a step up from PHP. Some of the language quirks bother me but overall I think it's worth learning more. What I really wish was out there was a Groovy syntax language that didn't require a JVM and was more like PHP/Python.
Title: Re: Anyone use Python?
Post by: webwhy on May 14, 2012, 10:29:14 AM
in my opinion you're describing Ruby (MRI or CRuby).  faster startup than JVM with the C based interpreter.  It's implementation and language syntax was a big inspiration for Groovy's, especially concerning blocks, which make all of the awesome collection stuff possible.

Code: [Select]
# sum squares from 1 to 10
1.upto(10).map { |num| num**2 }.reduce(0) { |sum, num| sum += num }
Title: Re: Anyone use Python?
Post by: hans on November 05, 2012, 11:23:34 PM
So after spending some serious development time with Python I've grown quite fond of it. There are still a few silly things but I keep figuring out ways to get around things.

Like the Elvis operator in Groovy where the value gets used if it evaluates to true:
def max = params.max ?: 10

Can be done similarly and perhaps more readable in Python:
max = params.max or 10

I'm almost done with a functional prototype of a cloud based PBX system using the Tropo WebAPI that I build using Python with Flask, WTForms, SQLAlchemy (and a few others) setup. After spending some time playing with Go (golang) I like the toolkit (library) approach vs full on convention framework. For smaller apps that don't use many of the framework features it just makes the apps seem bulky. And since I'm becoming a big fan of an API micro-app design mentality, the smaller frameworks fit better into that, only pull in what you need. I think once I get a little bit better feel for the development I'm going to try and start making some helper packages that I can pull in and get going even quicker. It seems rather easy to setup a skeleton application to start from.

In another week or so I might have a demo for you guys to play with for the PBX system. I'm pondering where to host it at the moment. I sort of want to give AppEngine a shot but it will probably live on a box in my office for a little bit.
Title: Re: Anyone use Python?
Post by: JaWiB on November 06, 2012, 12:53:35 AM
PBX?
Title: Re: Anyone use Python?
Post by: hans on November 06, 2012, 08:15:57 AM
Phone system. Think virtual receptionist. Often companies need to buy hardware and phones but really, why bother if everyone has mobiles and might not even be in the office at all. And this system could be on demand in a matter of minutes.
Title: Re: Anyone use Python?
Post by: Mike on November 30, 2012, 12:19:06 AM
This last weekend I wrote my first non-trivial python script to pull xml data from a website and add relevant data to a Google spreadsheet.  Today I started working on a python task at work.  I'm really starting to warm up to it.  I really did the list comprehension stuff.
Title: Re: Anyone use Python?
Post by: Mike on December 02, 2012, 11:29:03 PM
Found one area where python is really lacking compared to php:  date/time handling.  It is so freaking awesome to drop a string into strtotime() and be done with parsing it.  Even with the dateutil 3rd party lib I'm still running into problems with python.
Title: Re: Anyone use Python?
Post by: ober on December 03, 2012, 12:10:39 AM
Java is the same way.  I fucking hate dealing with dates in Java.
Title: Re: Anyone use Python?
Post by: Perspective on December 03, 2012, 08:26:40 AM
Java is the same way.  I fucking hate dealing with dates in Java.

SimpleDateFormat ?  You just specify the format as a String and it parses it as a Date.
Title: Re: Anyone use Python?
Post by: ober on December 03, 2012, 09:27:27 AM
Eh... maybe I haven't used that one?  I have been using Calendar and Date.  I know Date is deprecated so I've been trying to use Calendar.  Again... Java provides so many classes to do the same damn thing, that you often don't know the best one to use.
Title: Re: Anyone use Python?
Post by: Perspective on December 03, 2012, 09:52:30 AM
yeah man, don't use Date. I haven't tried Calendar, but SimpleDateFormat is probably what you're looking for
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
Title: Re: Anyone use Python?
Post by: micah on December 03, 2012, 11:34:39 AM
Java is the same way.  I fucking hate dealing with dates in Java.

on a somewhat unrelated note, I was getting really annoyed with Javascript for a project recently that had a LOT of date formatting so I made a function that works just like the PHP Date function that I know and love.

https://gist.github.com/4120120

kinda off topic, but just thought I'd share
Title: Re: Anyone use Python?
Post by: Mike on December 03, 2012, 12:09:42 PM
Java is the same way.  I fucking hate dealing with dates in Java.

on a somewhat unrelated note, I was getting really annoyed with Javascript for a project recently that had a LOT of date formatting so I made a function that works just like the PHP Date function that I know and love.

https://gist.github.com/4120120

kinda off topic, but just thought I'd share
Since I almost always have jquery and jqueryui loaded: http://api.jqueryui.com/datepicker/#option-dateFormat
Title: Re: Anyone use Python?
Post by: hans on December 03, 2012, 02:22:33 PM
In the Java world, use joda time library for dates. Much better.
Title: Re: Anyone use Python?
Post by: JaWiB on December 04, 2012, 09:54:39 PM
So what's the deal with Python 3? Should I be using that instead of 2.whatever? Everything seems to use python 2...
Title: Re: Anyone use Python?
Post by: Perspective on December 05, 2012, 10:48:52 AM
Python 3 broke backwards compatibility which could affect your ability to use existing libraries. I'm still sticking with 2.x for everything I do.
Title: Re: Anyone use Python?
Post by: hans on December 05, 2012, 08:31:08 PM
Python 2.x is still what's mostly supported everywhere. Python 3 is the new hotness bit looks like it might take a while for it to be the default unless you're running your own server.

I'm using 2.x for my stuff, but from what I gather you can code in a py3 manner to make the code work in both.
Title: Re: Anyone use Python?
Post by: Mike on December 23, 2012, 05:57:12 PM
I'd like to take a moment during this holiday season to say:  I'm sorry, I was wrong about Python.  It is a pretty damn nice language.
Title: Re: Anyone use Python?
Post by: Mike on December 23, 2012, 06:00:35 PM
You may be tempted to start writing

from ls331 import *

This is generally frowned about. Python people have a hard-on for explicit imports.

At work we just went through that discussion.  We had something like:
Code: [Select]
from handlers import (user_routes, quest_routes, etc etc etc,
                                   more routes, even more routes, routes,
                                   yet even more routes)
Once it got to three lines I put in a PR request to just change it to
Code: [Select]
from handlers import *
The only real downside is that flake8 can't tell us if we fucked up one of the handler names now.  But unit tests handle most of that.
Title: Re: Anyone use Python?
Post by: JaWiB on December 24, 2012, 12:25:03 AM
Funny, I was just thinking that your import statements could get ridiculously long in certain cases and wondering at what point I should break that rule.
Title: Re: Anyone use Python?
Post by: hans on December 24, 2012, 10:03:00 AM
That kind of problem also make me wonder if that module might be responsible for too much stuff. Sometimes it might be appropriate but I think the explicit import method makes you think a bit more.
Title: Re: Anyone use Python?
Post by: Mike on December 24, 2012, 10:12:37 AM
That kind of problem also make me wonder if that module might be responsible for too much stuff. Sometimes it might be appropriate but I think the explicit import method makes you think a bit more.
In our case I don't think it is responsible for too much.  Our other options would be to use fewer handler files or to do
Code: [Select]
import handlers

handlers.user_routes.bleh
which would be more specific.
Title: Re: Anyone use Python?
Post by: Mike on February 13, 2013, 01:56:45 AM
So the last week or so I've been doing some JS and been getting annoyed with having to use {} instead of just indenting it.  Oh how things change :D