Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Mikey-San
Nov 3, 2005

I'm Edith Head!

tripwire posted:

Why [not use try/except]?

Because it makes more sense simply to ask if the instance responds to a method before attempting to invoke it. Why generate exceptions and write exception handling code when neither is necessary? (edit: basically, i get really sick of writing exception handling code constantly in python, so sometimes i just find out if i should attempt something before doing it. i find i wind up dealing with and masking fewer problems if i avoid a try/except block where i can. feel free to convince me i'm still Doing It Wrong, i'll always listen.)

quote:

Actually the real question is why he isn't using hasattr().

The hasattr() function just tells you whether or not an attribute exists, not whether it's actually callable. Also, what Milde said about swallowing exceptions.

Mikey-San fucked around with this message at 09:07 on Sep 20, 2009

Adbot
ADBOT LOVES YOU

Sylink
Apr 17, 2004

Can anyone recommend any python libraries for image pattern recognition?

I want something made for it not OCR. I want to do something simple like find all the circles in an image or something like that , not full blown FBI forensics.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Sylink posted:

Can anyone recommend any python libraries for image pattern recognition?

I want something made for it not OCR. I want to do something simple like find all the circles in an image or something like that , not full blown FBI forensics.

You have two options, either use PIL and code the kernel functions and algorithms yourself (basing yourself on PIL's Filters).

Or you use an OpenCV SWIG interface.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

Mikey-San posted:

Because it makes more sense simply to ask if the instance responds to a method before attempting to invoke it. Why generate exceptions and write exception handling code when neither is necessary? (edit: basically, i get really sick of writing exception handling code constantly in python, so sometimes i just find out if i should attempt something before doing it. i find i wind up dealing with and masking fewer problems if i avoid a try/except block where i can. feel free to convince me i'm still Doing It Wrong, i'll always listen.)

In this case, I like your way of doing it a little more. But in general, I was of the impression that asking forgiveness rather than permission was the slightly more pythonic way to handle things. Not every case lets you use a nice builtin like callable(), though.

unixbeard
Dec 29, 2004

hey

Was wondering if i could get some feedback on some code http://pastebin.com/d496be86c

I have an object with multiple attributes (class Simple in the example). I then have a container object (Cont) for a collection of Simples, for which i've used a dictionary with a datetime key.

In practice, each day i get new values for Simple to remember, this is why i am using a datetime key. I will also have many instances of Cont, each with their own respective Simples.

Basically i wanted to be able to go Cont.xs[n] which would give be the x value for date n. I also wanted this to support slices.

So, 'xs' is a property of Cont, which uses a psuedo anonymous object to override __getitem__ for the dict in Cont. I could not use normal properties as I couldn't see a way that they let me support the slice operator, as they only have get/set/del. The attrproperty code is from here http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/

I'm still learning python, so if there is a better way to do this or something in the standard library that would be better I'd love to know.

It would be cool if i could abstract it so i didn't need to copy and paste the code like i do for 'xs' and 'ys', as in the real version I'll have several variables I'll want to handle like this.

It would also be cool if it wasn't super slow. I'm sure all those list sorts will add up over time.

I've intentionally left the step part of the slice as an integer rather than something like a timedelta, because i'm not yet sure how i'll handle different timedeltas in my application and this will do for now.

thanks

unixbeard fucked around with this message at 00:07 on Sep 24, 2009

RobotEmpire
Dec 8, 2007
I completed my first real python project a few days ago (with Django even). Now I'm starting on something real that I would hope would eventually be used in production.

My first step that I'm having some trouble with is importing a report from an MS-Access database. I picked up pyodbc but I'm having trouble actually importing the files. I get the following error:

http://dpaste.org/RBiJ/

Does anyone have any familiarity with SQL Server? Or point me somewhere I can ask?

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.
Been a long time since I've been near it but back in the day Access and SQL Server used entirely different connection strings. Check out http://www.connectionstrings.com/

unixbeard
Dec 29, 2004

yeah i think you want to be using the Jet oledb driver. Using SQL Server will make it look for an actual SQL Server.

If you want to actually use SQL Server theres a free version called SQL Server Express http://www.microsoft.com/express/sql/default.aspx

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...
A bit of gratuitous self publicity: I've pushed the latest version of rst2beamer to Pypi.

What it does: it's a tool for making quick and-dirty-presentations. More specifically, it converts restructured text to LateX, specifically the Beamer flavour that can be used for talks / slides / etc.

The back story: some years ago, I had to do a lecture series that saw me having to produce 40 teaching slides a day. Using Powerpoint or Keynote was too slow and fiddly (paste in code segment, adjust styles, move page elements about ...) so I wrote this quick hack to pour simple text in the form of ReST into a presentation: ReST to LaTeX to PDF. It saved me a huge amount of time. Last year another lecturer in the US took it over, and we've been making small incremental changes since. It's not - and isn't meant to be - a rival to proper presentation software, but it is handy for throwing up a bunch of bullet points and pictures. Enjoy.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I'm writing some stuff that interacts with utorrent via it's Web API.

One of the things I do is create a dictionary of utorrent settings like this:

code:
utsettings['downloaddir'] = "C:\downloads"
I have a function like this:

code:
def change_setting(setting, value):
So when I want to change something I call it like this:

code:
change_setting('downloaddir', 'D:\new_download_dir')
It would be awesome if I could somehow automatically call change_setting() when I modify the dict utsettings. Possible? Stupid? Advice?

ErIog
Jul 11, 2001

:nsacloud:

Thermopyle posted:

It would be awesome if I could somehow automatically call change_setting() when I modify the dict utsettings. Possible? Stupid? Advice?

Why don't you have your change_setting function submit the change, and then modify the dict with that information? I mean, if you're changing the setting yourself, then you're going to want your dict to keep track of it.

ErIog fucked around with this message at 21:50 on Sep 24, 2009

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.

Thermopyle posted:

It would be awesome if I could somehow automatically call change_setting() when I modify the dict utsettings. Possible? Stupid? Advice?
You can subclass dict and override its __setitem__ method that gets called every time you add/update a keyvalue pair:
code:
class Settings(dict):

	def __setitem__(self, key, value):

		# call change_setting() here
		dict.__setitem__(self, key, value)

settings = Settings()
settings["foo"] = "bar" # __setitem__ gets called here automatically

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

ErIog posted:

Why don't you have your change_setting function submit the change, and then modify the dict with that information? I mean, if you're changing the setting yourself, then you're going to want your dict to keep track of it.

Yeah, this is actually what I do now.

It just seems like it would be more...I dont know..."objecty" and elegant if by modifying the dict I was actually modifying the setting.

This was more idle thought than something I've got to do...

jupo posted:

You can subclass dict and override its __setitem__ method that gets called every time you add/update a keyvalue pair:
code:
class Settings(dict):

	def __setitem__(self, key, value):

		# call change_setting() here
		dict.__setitem__(self, key, value)

settings = Settings()
settings["foo"] = "bar" # __setitem__ gets called here automatically

oooo. I get it, thanks!

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Ok, completely different question...

I'm starting on my first projects that I think will benefit from splitting into more than one file.

To start out with I'm taking a long-ish script I wrote and dividing it into several files. What's the best way to handle utility functions that are used both in my main file and in the modules that I import?

No Safe Word
Feb 26, 2005

Thermopyle posted:

Ok, completely different question...

I'm starting on my first projects that I think will benefit from splitting into more than one file.

To start out with I'm taking a long-ish script I wrote and dividing it into several files. What's the best way to handle utility functions that are used both in my main file and in the modules that I import?

code:
utils.py
main.py (import utils)
moduleA.py (import utils)
moduleB.py (import utils)
or if it's appropriate (ie, there's a sub-theme which has many distinct modules), break moduleA and moduleB into directories.

Lurchington
Jan 2, 2003

Forums Dragoon
I've run into this a few times while working on projects, but you need to be careful about circular imports. For example, I originally had a file that contained all the "public" unit tests for my program, and imported practically every module at the top.

In those modules, I had some private unit tests that imported a subclassed unittest from that original file, and there were issues.

This was solved easily enough, but if you go to the trouble of breaking things out into modules and then start seeing weird errors, it's at least worth checking on.

maskenfreiheit
Dec 30, 2004
Edit: doublepost

maskenfreiheit fucked around with this message at 01:20 on Mar 13, 2017

Scaevolus
Apr 16, 2007

GregNorc posted:

Basically I'm wondering:
1.) Is it possible to have a list of objects? (So I could use pythons shuffle() on a list of cards)
2. Is it possible to write some sort of loop to create these card objects, rather than do it all by hand? (I'm guessing yes)
1.) Yes.
2.) Yes.

However, I would recommend using tuples instead of classes. Your card object would only be storing two pieces of information-- rank and suit. Just using a (rank, suit) tuple would simplify things plenty.

RobotEmpire
Dec 8, 2007

GregNorc posted:

So I've been reading through the python tutorial... I'm learning python, and the en d goal is a simple blackjack program.

I had originally planned to create the deck by creating a list of ordered pairs.

Suit would be 0-3, rank would be 0-12, and I'd make a loop to create a list with those pairs...

However upon coming to the section on classes it seems like classes are perfect for this, but it's a bit confusing.

Ideally I'd like to have a set of cards like this:

card0.rank = 0
card0.suit = 0

card1.rank = 1
card1.suit = 1

.
.
.

card52.rank = 12
card52.suit = 3

Basically I'm wondering:
1.) Is it possible to have a list of objects? (So I could use pythons shuffle() on a list of cards)
2. Is it possible to write some sort of loop to create these card objects, rather than do it all by hand? (I'm guessing yes)

Any help is appreciated... the tutorial has been good so far but it's so abstract... it gives examples like a class called x with attribute y so you've got x.y which has a value of 12345... I mean I guess it explains it, but it's not very intuitive... I'd planned to wait to write code for the blackjack program until I finished reading the tutorial but I think writing at least the functions/methods to create and shuffle the deck would teach me more about classes since I'm completely stuck on the tutorial. (I can type the commands into the python interpreter but the code all sort of blends together and I have no deep understanding of _why_ things are happening)

Basically I'm not looking for an answer, but maybe a set of leading questions to put me on the right path. Thanks a lot!

Are you using Dive Into Python?

Also if you're going to go with classes you'd basically want a class called "Card", then assign attributes from there. You wouldn't want a class for every individual object. Not saying that's the best approach, or even a good/rational approach, but a class is just that -- a class (aka type) of objects. Like int, str, float, etc.

edit: My biggest and best recommendation is to find someone who is willing to answer your questions one-on-one as the problems arise.

edit2: Here is a snippet of another person's blackjack game. I haven't tested it but it might be worth looking through the program line by line and seeing how it works. That's the best way to learn.

RobotEmpire fucked around with this message at 06:25 on Sep 29, 2009

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...
Didn't spot this in the thread above but: virtualenv doesn't work with OSX Snow Leopard. It just whirs endlessly to itself. The problem is to do with circular symlinks apparently, and a working solution can be found here. (PS: installing from dev or subversion doesn't help.)

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

outlier posted:

Didn't spot this in the thread above but: virtualenv doesn't work with OSX Snow Leopard. It just whirs endlessly to itself. The problem is to do with circular symlinks apparently, and a working solution can be found here. (PS: installing from dev or subversion doesn't help.)

Yes, it does - except you need to install the bitbucket version, which AFAIK is the canonical version: http://bitbucket.org/ianb/virtualenv/ no need to deal with the mailing list. Ian really needs to nuke the old, out of date svn version.

king_kilr
May 25, 2007

m0nk3yz posted:

Yes, it does - except you need to install the bitbucket version, which AFAIK is the canonical version: http://bitbucket.org/ianb/virtualenv/ no need to deal with the mailing list. Ian really needs to nuke the old, out of date svn version.

Bitbucket is indeed the canonical one. You can tell because that's where Jannis Leidel was given commit :)

maskenfreiheit
Dec 30, 2004
Edit: doublepost

maskenfreiheit fucked around with this message at 01:20 on Mar 13, 2017

Mikey-San
Nov 3, 2005

I'm Edith Head!
You can't solve problems if you aren't aware of what tools are available to you.

RobotEmpire
Dec 8, 2007

Mikey-San posted:

You can't solve problems if you aren't aware of what tools are available to you.

This, so much this. Learning the general syntax of python is *EASY*. It's just a matter of learning what commands are available at your disposal, and how/when to use them.

Mikey-San
Nov 3, 2005

I'm Edith Head!

RobotEmpire posted:

This, so much this. Learning the general syntax of python is *EASY*. It's just a matter of learning what commands are available at your disposal, and how/when to use them.

Learning the syntax is the easy part of any language. Memorizing methods and APIs is just a matter of repetition (and documentation). The difficult part is learning how to leverage the mindset of a language to solve your problems better than you could before.

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...

m0nk3yz posted:

Yes, it does - except you need to install the bitbucket version, which AFAIK is the canonical version: http://bitbucket.org/ianb/virtualenv/ no need to deal with the mailing list. Ian really needs to nuke the old, out of date svn version.

Input appreciated m0nk3yz but: a description of the bitbucket solution is what I pointed at. If you try to install via vanilla setuptools (easy_install virtualenv) you get the old, broken version. So the canonical version isn't very canonical in terms of that, which is a bit of a problem, and from the mailing list many people are falling into that trap.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

outlier posted:

Input appreciated m0nk3yz but: a description of the bitbucket solution is what I pointed at. If you try to install via vanilla setuptools (easy_install virtualenv) you get the old, broken version. So the canonical version isn't very canonical in terms of that, which is a bit of a problem, and from the mailing list many people are falling into that trap.

Fair enough - I sort of assume(d) everyone knew this; I stopped using easy_install for anything - and when using pip (pip is awesome), I go out of my way to use the git/hg/svn (pip handles all of these) repos for most anything else. I've been burned enough by things like this (stale svn, busted pypi entries).

Argh; packaging/installation of 3rdparty modules makes me so angry.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

m0nk3yz posted:

Argh; packaging/installation of 3rdparty modules makes me so angry.

Seriously this is one thing that Perl got right.

Lurchington
Jan 2, 2003

Forums Dragoon
I switched over to developing Python on the Mac (from Windows, now on Snow Leopard), and I just wanted to go ahead and complain about how much of a pain in the rear end it is to get Xcode 3.2 working with PyObjC.

I really just wanted to have Xcode doing some syntax highlighting and invoke the run command, but it's more a hassle than I want to deal with on a Saturday.

I used to use SPE on the Mac, but it's always been irregularly maintained and I haven't googled a way to get a python 2.6-compatible package.

What are Snow Leopard people using to develop?

king_kilr
May 25, 2007
Gedit! http://projects.gnome.org/gedit/ Look at that loving text editor: http://blogs.gnome.org/pbor/files/2008/12/geditosx.png

Mikey-San
Nov 3, 2005

I'm Edith Head!

king_kilr posted:

Gedit! http://projects.gnome.org/gedit/ Look at that loving text editor: http://blogs.gnome.org/pbor/files/2008/12/geditosx.png

Yes, look at how loving out of place and awkward it looks on Mac OS X.

blorpy
Jan 5, 2005

Gedit is loving terrible, haha.

tripwire
Nov 19, 2004

        ghost flow

Markov Chain Chomp posted:

Gedit is loving terrible, haha.

Its not so bad! :(

I like it better than idle anyway

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

king_kilr posted:

Gedit! http://projects.gnome.org/gedit/ Look at that loving text editor: http://blogs.gnome.org/pbor/files/2008/12/geditosx.png

Dude. Seriously?

Serious options Lurchington - check out TextWrangler (http://www.barebones.com/products/TextWrangler/), TextMate (http://macromates.com/), MacVim (http://code.google.com/p/macvim/), and PyDev (http://pydev.org/).

I swap between textmate and macvim personally.

Haha GEdit? Whut.

Lurchington
Jan 2, 2003

Forums Dragoon
I've used TextWrangler a fair amount, but I realize I left off a few of the features I was looking for:

  • class/function browser to flip between different parts of the file
  • function tooltis (for example, open parantheses and I see what arguments I need)

I don't really expect this anywhere outside of PyScripter (windows-only), I did also like unittest integration.

I'll check out the ones you list, I had originally looked for more than I typically expect in a text editor.

edit: TextMate seems to bring in some of the convenience I was looking for, thanks.

Lurchington fucked around with this message at 15:10 on Oct 4, 2009

unixbeard
Dec 29, 2004

Lurchington posted:

What are Snow Leopard people using to develop?

i use eclipse on os x for java, i have previously used pydev eclipse plugin on windows which i thought was pretty good. in fact im thinking of installing it since i have eclipse here anyway

tripwire
Nov 19, 2004

        ghost flow
Is there an equivalent of the builtin function zip that works on numpy arrays?

edit: Er, actually that's not quite what I meant. I'm looking at some audio code that splits a sample into the left and right channel, like so:

left, right = sample[1::2],sample[0::2]

After doing some processing on them I'd like to rejoin them back to how they were so I can write to the soundcard. Anyone done something like that before?

tripwire fucked around with this message at 18:13 on Oct 4, 2009

MagneticWombats
Aug 19, 2004
JUMP!
I have an XML file (from the GCIDE project if you're wondering) and I want to parse it. The only problem is that none of the parsers (except maybe SAX, but I don't want to use SAX) seem to support external entities. Is there some way around this?

Adbot
ADBOT LOVES YOU

maskenfreiheit
Dec 30, 2004
Edit: Double Post

maskenfreiheit fucked around with this message at 20:34 on Mar 13, 2017

  • Locked thread