EntropySink
Technical & Scientific => Programming => Topic started 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
-
I don't but I keep meaning to get competent. I still maintain that using indention for block level control is just fucking stupid.
-
Yeah, I miss my curly braces. And semicolons.
-
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.
-
I use Python all day.
Duck typing won't stop you from creating base classes. That would be awful.
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():
...snip...
@property
def temp(self):
return self._temp - 3
...
controller = TempControllerA(45)
controller.temp #temp is a read-only property now.
-
That looks fucking awful. I'll stick to PHP and Java.
-
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)
-
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
-
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
-
I should note you could write everything more succinctly this way (this is from an interactive REPL session, hence the dots and >>).
>>> 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.
-
-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.
-
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:
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"
-
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++
-
-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.
-
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.
-
-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.
-
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.
-
I was reading about properties and the guy wrote this:
@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"""
-
Thanks -Ken-. Hopefully, once I get these current projects done I'll have more time to check that out.
-
I was reading about properties and the guy wrote this:
@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.
-
Here's the blog article: http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/
-
Yeah, that just plain doesn't work.
>>> 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 '
-
I was reading about properties and the guy wrote this:
@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.
-
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__
-
Either of you guys use eclipse? Is there a way to debug using the interactive console?
-
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.
-
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.
-
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++:
#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.
-
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:
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?
-
you can also use "from ls331 import LS331"
-
Oh, nice, thanks!
-
You may be tempted to start writing
from ls331 import *
This is generally frowned about. Python people have a hard-on for explicit imports.
-
Re: debugging, you can use this -- http://docs.python.org/library/pdb.html
I'm more a traceback-and-tinker sort of debugger ;)
-
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.
-
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.
# sum squares from 1 to 10
1.upto(10).map { |num| num**2 }.reduce(0) { |sum, num| sum += num }
-
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.
-
PBX?
-
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.
-
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.
-
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.
-
Java is the same way. I fucking hate dealing with dates in Java.
-
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.
-
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.
-
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
-
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
-
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
-
In the Java world, use joda time library for dates. Much better.
-
So what's the deal with Python 3? Should I be using that instead of 2.whatever? Everything seems to use python 2...
-
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.
-
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.
-
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.
-
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:
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 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.
-
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.
-
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.
-
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
import handlers
handlers.user_routes.bleh
which would be more specific.
-
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