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
m0nk3yz
Mar 13, 2002

Behold the power of cheese!
Ok, so a question for all of you. I'm moving forward with a project to design a ton of function tests in Nose - the problem being, each test needs to be "told" about the attributes of the system under test (ip addresses, etc). I can do a few things:
  • use plain text name=value, and have nose parse it and pass it into the tests
  • use YAML (mainly for object instantiation and more advanced stuff) and have the tests (or nose) parse it and pass it in. The bonus here is that I automagically get objects of the specified type, and I don't need additional parsing/coercion.
  • Use a ConfigParser style file, and do the type parsing/coercion myself.
  • Write a test-configuration plugin for nose to do all of this and pass it into the tests. Make the underlying data format irrelevant to the tests.
I'm open to thoughts - just weighing the various options before running off and doing it.

Adbot
ADBOT LOVES YOU

hey mom its 420
May 12, 2007

How about you just write it into a dict in Python syntax and then import the dict?
edit: or just set variables and then import the module. You know, like if you have test_settings.py and then in it you do
code:
ip_numbers = ["192.168.1.1", "132.242.222.111", "192.168.1.100"]
blah = 20420
something = 203.20
and then just do import test_settings and so it's handy to access the values like test_settings.blah

hey mom its 420 fucked around with this message at 22:15 on Jul 7, 2008

Hanpan
Dec 5, 2004

Wow. After being recommended pyGame over in the Game Development thread, I have been trying to figure out how to get python / pygame and setup with a decent IDE on Mac OSX.

Can anyone point me in the direction of a simple step by step tutorial to getting things up and running? All the stuff on the pygame website is pretty advanced.

Scaevolus
Apr 16, 2007

Hanpan posted:

Wow. After being recommended pyGame over in the Game Development thread, I have been trying to figure out how to get python / pygame and setup with a decent IDE on Mac OSX.

Can anyone point me in the direction of a simple step by step tutorial to getting things up and running? All the stuff on the pygame website is pretty advanced.

Did you try http://rene.f0o.com/mywiki/PythonGameProgramming? It looks pretty reasonable.

ATLbeer
Sep 26, 2004
Über nerd

Hanpan posted:

Wow. After being recommended pyGame over in the Game Development thread, I have been trying to figure out how to get python / pygame and setup with a decent IDE on Mac OSX.

Can anyone point me in the direction of a simple step by step tutorial to getting things up and running? All the stuff on the pygame website is pretty advanced.

I always check PythonMac for packages first when installing a big package. These are nice tested pkg installers for OS X that have always worked goldenly for me. PyGame is included there

http://pythonmac.org/packages/py24-fat/index.html

uncleTomOfFinland
May 25, 2008

I have been trying to script a little bit with Python on Windows XP but I have run into this weird problem I can't figure out.

code:
import os
os.system('''robocopy <switches and other crap go here>''')
When I execute the script I get nothing but a blank command prompt window and it would seem the program is looping somehow. But the weirdest thing is that it works perfectly fine if I type it line by line in the interactive shell so its not the string syntax, I guess. :confused:

Any regular commands like 'dir && pause' work fine too.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Pavol Paska posted:

I have been trying to script a little bit with Python on Windows XP but I have run into this weird problem I can't figure out.

code:
import os
os.system('''robocopy <switches and other crap go here>''')
When I execute the script I get nothing but a blank command prompt window and it would seem the program is looping somehow. But the weirdest thing is that it works perfectly fine if I type it line by line in the interactive shell so its not the string syntax, I guess. :confused:

Any regular commands like 'dir && pause' work fine too.

It's probably trying to read something from stdin, which is set up right in the interactive shell but not when running as a script. (I'm guessing from your description, that is, I'm not actually sure when stdin is set up and not set up under Windows.)

Try running it as "python -i /your/script/name" and see if that fixes it. It should run and then give you the interactive shell.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


I ran into an issue when attempting to retrieve a slice from a container class I had created. The docs seem to imply that __getslice__() has been deprecated since 2.0 so I didn't bother to declare it in my class definition. However, once I added it my code magically worked. What gives? I can see why it would be deprecated as __getitem__ should be enough to pull a slice. But why is that bit about deprecation in the docs if I still have to declare it? Is that just wishful thinking?

duck monster
Dec 15, 2004

bosko posted:

Has anyone gotten PayPal IPN working with Python? For the life of me I can't figure out what I am doing wrong when I have simply taken the idea from another (working) script and used it in my own.

I am not getting errors, it just seems PayPal cannot verify my payment and therefore nothing is happening unless the user explicitly clicks on "Return to Merchant" which then everything is grand, but not every user clicks that link

This is a mix of django/python but the relevant stuff is in Python

PP_URL = https://www.paypal.com/cgi-bin/webscr

code:
newparams = {}
    for key in request.POST.keys():
        newparams[key] = request.POST[key]

    newparams['cmd'] = '_notify-validate'

    params = urlencode(newparams)

    req = urllib2.Request(PP_URL)
    req.add_header("Content-type", "application/x-www-form-urlencoded")
    fo = urllib2.urlopen(PP_URL, params)

    ret = fo.read()
    if ret != 'VERIFIED':
        return HttpResponse('Could not verify PayPal Payment')


# Other code to store information into cart

return HttpResponseRedirect('....') # Redirects the user if everything was A-OK
Any ideas what I could be doing wrong? Thanks in advance.

Paypal are the devil. Do not trust your business to those cunts. Seriously, I blame their worthless system for my current unemployment.

hey mom its 420
May 12, 2007

No, __getslice__ is deprecated, don't use that. Make sure that you have a new-style object there. So if you have
code:
class Collection:
  def __init__(self, data)
    self.data = data
  def __getitem__(self, key)
    return self.data.__getitem__(key)
That won't work, because you have to do make it a new-style object. So you'd have to have
code:
class Collection(object):
  # stuff goes here
in Python 2.5, objects are considered old style objects unless they inherit from the object. In py3k, you won't have to do that anymore.

duck monster
Dec 15, 2004

Flea110 posted:

I've spent the last week or so writing a battle simulator for the board game Axis & Allies. I'm fairly new to programming, and it's my first program that uses classes.

I'd appreciate any constructive criticism, or any other advice or opinions.

http://pastebin.com/f741d6759

Its not bad, but I get the feeling your still sort of writing structured code just wrapped in objects. Its still a valid way of coding, but its not the best way.

Heres how to look at objects and do it right;-

Disclaimer: I'm an OO Design zealot, so take this with moderation if you don't want to grow an absurd neckbeard and start developing erections at the mere mention of smalltalk.

An object is a little black box, that you can make lots of copies of, and it has properties and methods. Methods being best thought of as "code that happens when an object is sent a message" (You send the message by calling the method). All understood right? One needn't care whats *in* the black box, as long as the properties and methods behave as expected. A black box is a model of a thing, an object , so to speak. Your program is an object. The Countries are objects, the board pieces are objects. The players are objects And so on.

So you might for instance write a country object that has a property like "who is occupying me?" and "How many troops are here". And then perhaps add methos like "add_troops([list of troop objects],player,where_troops_came_from)" or "send_troops([list of troop objects],player,where_troops_go_to)", then maybe methods like "calculate_sovereignty" and "make_dudes_fight" or whatever

and so on until you have a model of how a country in the game follows the rules and gains/loses sovereignty and so on.

Then you do the same for troops/units

And add a player object (maybe you make this first)

and finally add a game object that controls and contains all the other guys.

With all that finished you might then create some objects that interact with the user.

It does sound like more work, but once you get the hang of it, its really intuitive, and it becomes second nature, and it fits neatly with the sort of methodologies you might work with in the 'serious programming world' like unit testing and UML and poo poo like that.

uncleTomOfFinland
May 25, 2008

JoeNotCharles posted:

It's probably trying to read something from stdin, which is set up right in the interactive shell but not when running as a script. (I'm guessing from your description, that is, I'm not actually sure when stdin is set up and not set up under Windows.)

Try running it as "python -i /your/script/name" and see if that fixes it. It should run and then give you the interactive shell.

Didn't fix it but for some bizarre reason using robocopy.exe instead of just robocopy works. I really love windows commandline tools sometimes.

Thanks anyway

Xenos
Jun 17, 2005

outlier posted:

What are people using for general HTML form generation? A lot of the more popular modules out there are tied to particular frameworks (e.g. zope.form, newforms). I really like formencode's validation and conversion but it doesn't generate forms (for good reasons) and has some oddities when handling arrays of fields. formbuild is supposed is okay, but again has a couple of odd design decisions.

You might want to look into ToscaWidgets, which is based on the TurboGears widgets package. It isn't actually dependent on TurboGears, though. I personally haven't used this, but it's going into TurboGears 2, and if it works anything like the original TurboGears widgets package, it'll work really well with FormEncode.

RyceCube
Dec 22, 2003
I'm new to python and i'm working on the Euler questions as a way to practice. I haven't touched programming in a few years and just started getting back into it, so forgive me if this is a stupid question.

I need to check if a number is divisible by the numbers 1 through 20.
http://pastebin.com/m61c9119d (probably cringe-worthy code)

I'm not sure if the way I'm doing it really works, and i'm kind of stuck on how to do so. If anyone could give me advice or point me in the right direction without writing 20 separate if statements, that would be awesome.

uncleTomOfFinland
May 25, 2008

Phiberoptik posted:

I'm new to python and i'm working on the Euler questions as a way to practice. I haven't touched programming in a few years and just started getting back into it, so forgive me if this is a stupid question.

I need to check if a number is divisible by the numbers 1 through 20.
http://pastebin.com/m61c9119d (probably cringe-worthy code)

I'm not sure if the way I'm doing it really works, and i'm kind of stuck on how to do so. If anyone could give me advice or point me in the right direction without writing 20 separate if statements, that would be awesome.

You mistyped range() at least. Use 2,21, not 2-21. :)

EDIT: Check is referenced before its assigned too.

EDIT:

This little snippet returns a list that contains all the numbers between 2 and 20 x is divisible by:
code:
[i for i in range(2,21) if x % i == 0]

uncleTomOfFinland fucked around with this message at 08:34 on Jul 14, 2008

RyceCube
Dec 22, 2003

Pavol Paska posted:

You mistyped range() at least. Use 2,21, not 2-21. :)

EDIT: Check is referenced before its assigned too.

EDIT:

This little snippet returns a list that contains all the numbers between 2 and 20 x is divisible by:
code:
[i for i in range(2,21) if x % i == 0]

Thanks! I had check assigned, but didn't include it in the pastebin. I'll tinker with this and see how it goes.

edit: I'm trying to use sqrt for a problem, but I keep getting this error:

code:
global name 'sqrt' is not defined
Any idea why?

RyceCube fucked around with this message at 11:23 on Jul 14, 2008

WickedMetalHead
Mar 9, 2007
/dev/null
did you import math?


something like

code:
import math

math.sqrt(10)

zero knowledge
Apr 27, 2008
Because I'm a pedant: to do it somewhat more neatly and avoiding some namespace clutter,

code:
>>> from math import sqrt
>>> sqrt(10)
3.1622776601683795
>>> 

such a nice boy
Mar 22, 2002

Help me out, y'all; I'm preparing for a job interview this afternoon and I'm trying to think of all the questions they could possibly ask. I know that "what feature would you most like added to language X" is a popular question, but I can't think of anything for Python. So...what feature would you most like added to Python?

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

such a nice boy posted:

Help me out, y'all; I'm preparing for a job interview this afternoon and I'm trying to think of all the questions they could possibly ask. I know that "what feature would you most like added to language X" is a popular question, but I can't think of anything for Python. So...what feature would you most like added to Python?

One of the strange things about Python is that the things that used to bug me have mostly been fixed over the years. Still, here's some outstanding items:

* There's a bunch of ubiquitous and widely used 3rd party libraries that really should be in the standard library. I'm thinking of PIL, more advanced database interaction (something like JDBC), a better standard GUI than Tk and so on.

* Not everyone uses them, but it would be neat to have interfaces as part of the standard library (rather than the complex monolith that is zope.interface).

* Lot's of people hate using 'self' in objects. Personally, I'm indifferent.

* In-place increment and decrement (x++, x--) would be nice.

* Unicode as the standard string would be nice, and that's coming in Python3000.

* Multi-line and more sophisticated lambdas, oh yes.

bitprophet
Jul 22, 2004
Taco Defender

Spazmo posted:

Because I'm a pedant: to do it somewhat more neatly and avoiding some namespace clutter,

code:
>>> from math import sqrt
>>> sqrt(10)
3.1622776601683795
>>> 

Technically this doesn't actually avoid any namespace clutter, both approaches add a whopping one new name to the local namespace :) However, this approach does save typing if you use the imported function many times.

Allie
Jan 17, 2004

Python's lambdas are perfectly capable. They're meant for quick one statement functions that you pass to other functions. If you need more than one statement, you just make a function and pass the function. :)

I honestly don't understand why there's been so much whining over them, and I'm not really sure why Guido even considered removing them in the first place.

tef
May 30, 2004

-> some l-system crap ->

such a nice boy posted:

So...what feature would you most like added to Python?

where/with:

code:
x = foo(dave,3,5,toot) where:
    def dave(x):
        return x*2
    toot="cocks"

uncleTomOfFinland
May 25, 2008

Spazmo posted:

Because I'm a pedant: to do it somewhat more neatly and avoiding some namespace clutter,

code:
>>> from math import sqrt
>>> sqrt(10)
3.1622776601683795
>>> 

Do you happen to like PHP by any chance?

bitprophet
Jul 22, 2004
Taco Defender

Pavol Paska posted:

Do you happen to like PHP by any chance?

In his defense, doing from math import sqrt is perfectly Pythonic; the "lulz PHP's approach is awsum!" attitude would be closer to from math import * :)

zero knowledge
Apr 27, 2008

Pavol Paska posted:

Do you happen to like PHP by any chance?

Never done any, and I'm told I should be happy about it.

I just don't like typing math.sqrt(whatever) all the time. I suspect what you mean is that it's better if I know where the sqrt function comes from when I'm calling it, and I tend to agree, but if I'm just doing something on the Python console, the extra keystrokes are a bit annoying.

Allie
Jan 17, 2004

bitprophet posted:

In his defense, doing from math import sqrt is perfectly Pythonic; the "lulz PHP's approach is awsum!" attitude would be closer to from math import * :)

import * isn't inherently bad, but you generally shouldn't use it for modules that aren't designed for it (i.e. they don't have __all__ set). It can also confuse some lint tools like PyLint and Pyflakes and make it harder to statically find undefined names.

bitprophet
Jul 22, 2004
Taco Defender

Milde posted:

import * isn't inherently bad, but you generally shouldn't use it for modules that aren't designed for it (i.e. they don't have __all__ set). It can also confuse some lint tools like PyLint and Pyflakes and make it harder to statically find undefined names.

Oh, certainly, I was simply pointing out that if one is going to try and draw parallels between a given Python import syntax variant, and PHP, the "import *" one is closest to PHP's "haha namespacing what's that".

My rule of thumb is generally to use the * when I hit a confluence of A) using the imported names more than two or three times each and B) needing more than, say, 3 or 4 of the names within the module in question.

In a semi related note, I'm embarrassed to admit that I only really "got" PEP8 about a month or two ago (despite being primarily a Python coder for the past 4 years), and until then would sort of haphazardly mix things up. Still not a PEP8 saint but I've got the basics (e.g. foo, bar instead of foo,bar) down pat and it actually does make a difference in terms of the overall feel of the code.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


bitprophet posted:

In a semi related note, I'm embarrassed to admit that I only really "got" PEP8 about a month or two ago (despite being primarily a Python coder for the past 4 years), and until then would sort of haphazardly mix things up. Still not a PEP8 saint but I've got the basics (e.g. foo, bar instead of foo,bar) down pat and it actually does make a difference in terms of the overall feel of the code.

I've been using Python for about 2 years and I've been using nearly everything in PEP8 since the beginning, probably due to the book I was learning from (Learning Python). The only thing I had been doing differently was using lowerCamelCase for variable names. I just switched to underscored variables and it *feels* more Pythonic. Which probably sounds weird. But it does. I don't know.

A Perturbed Parrot
Nov 10, 2005

He was the kind of person who kept a parrot.
Quick Python question.
I'm presently working on a project which requires (and in fact is made much nicer by) the use of large databases.
After a quick look, I think I might use Python/MySQL mostly because it is free and rather easy to use, however, I'm open to any suggestion.
I don't really need a very elaborate database system just something robust, easy to use and manage. The application is not related to the web in any shape or form so "security" is not an issue at all.
Any good names to look up?
e:SQLite seems a solution I hadn't explored at first, any ideas about it?

A Perturbed Parrot fucked around with this message at 05:09 on Jul 21, 2008

Scaevolus
Apr 16, 2007

A Perturbed Parrot posted:

e:SQLite seems a solution I hadn't explored at first, any ideas about it?

SQLite is a very good choice if you need the features a database offers, but you don't need to have extremely high performance or support a huge load.

With a proper database abstraction layer, you can make it so that the choice between SQLite/MySQL/PostreSQL/whatever is just a configuration option.

Scaevolus fucked around with this message at 05:52 on Jul 21, 2008

Only Shallow
Nov 12, 2005

show
I'm attempting to compare data in the format "Sat, 12 Jul 2008 20:37:43 GMT -0500" to gmtime() with strptime(). Right now I have "%a, %d %b %Y %H:%M:%S %Z", but Python doesn't seem to have a time directive to handle the numeric GMT offset properly. What could I do to make this work, or am I even going about it in the best way?

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

A Perturbed Parrot posted:

Quick Python question.
I'm presently working on a project which requires (and in fact is made much nicer by) the use of large databases.
After a quick look, I think I might use Python/MySQL mostly because it is free and rather easy to use, however, I'm open to any suggestion.
I don't really need a very elaborate database system just something robust, easy to use and manage. The application is not related to the web in any shape or form so "security" is not an issue at all.
Any good names to look up?
e:SQLite seems a solution I hadn't explored at first, any ideas about it?

The only problem I've found with Python and MySQL is getting the library (MySQLdb) to compile. If you can pass that hurdle, it's fine. The Python Postgres libraries are okay. SQLite, although supposedly a dumb and simple solution works absolutely fine, is easy to use and performance is okay.

You may want to think about a database wrapper or ORM like SQLObject or SQLalchemy. It takes a while to get the hang of them but it makes it easy to change your db and deal in objects instead of rows.

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...
I've just discovered the wonders of appscript, a way to call Applescript from Python. It's cool, and recommended as much better than using Applescript directly. I hacked up a quick script to import a list of todo items into an application without an explicit Applescript dictionary. You can see it here, including some notes on a few holes or oddities I found.

ATLbeer
Sep 26, 2004
Über nerd
I have an odd problem. I have a RPC that is returning a dictionary but, unfortunately the dictionary is coming back as a string. It's a valid dictionary but, basically the __str__ version of the dict.

How can I cast the string back into a dictionary :\

Scaevolus
Apr 16, 2007

ATLbeer posted:

I have an odd problem. I have a RPC that is returning a dictionary but, unfortunately the dictionary is coming back as a string. It's a valid dictionary but, basically the __str__ version of the dict.

How can I cast the string back into a dictionary :\

I can't think of anything other than eval() or a similarly hacked-up parser :/

ATLbeer
Sep 26, 2004
Über nerd

Scaevolus posted:

I can't think of anything other than eval() or a similarly hacked-up parser :/

I guess that technically works

Allie
Jan 17, 2004

If you have to resort to that, you might want to do eval(x, {'__builtins__': ''}). That gets a little more complicated if you have objects that don't have literal representations, of course.

deimos
Nov 30, 2006

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

ATLbeer posted:

I guess that technically works

Is there any reason why you aren't using pickle to pass the objects around?

Or, if the dicts are simple enough, something like json.

Adbot
ADBOT LOVES YOU

m0nk3yz
Mar 13, 2002

Behold the power of cheese!
For those of you using nose, I uploaded a new configuration data plugin yesterday:

http://pypi.python.org/pypi/nose-testconfig/

It's a quick and dirty method of passing configuration data down to tests from within the context of nose.

  • Locked thread