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
deimos
Nov 30, 2006

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

m0nk3yz posted:

That's only partially true: Python can use multiple cores, python threads can not, as shown by effbot's recent wide-finder experiment (http://effbot.org/zone/wide-finder.htm). If you fork processes you can easily make use of multiple cores. Of course, fork/exec means you loose the shared context of pthreads.

Another thing that Fredrik's article pointed me towards when I first read it was defaultdicts, which are, in few words, loving awesome. :swoon: So much so that I went back through all my code looking for places to use them.

edit: OP: you might want to add this link up there:
Effbot's Python Standard Library book.

deimos fucked around with this message at 01:49 on Nov 5, 2007

Adbot
ADBOT LOVES YOU

deimos
Nov 30, 2006

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

inveratulo posted:

Frameworks like Zope or Django - these seem to have some kind of barrier to entry, lot of gotchas and I'm not sure I want to deal with those headaches just yet.

I can tell you this much: django can be as unobtrusive as you want it to be. The only thing you really can't change is the ORM, but it's also unobtrusive since you can do raw SQL with it.

Git posted:

Really though, Django might be overkill but it makes development fly by. I can't recommend it enough, but if you're absolutely certain that it won't suit, you might do well to look at the smaller frameworks like Pylons or CherryPy. Actually, you've a hell of a lot of frameworks you could choose from if any one doesn't suit.

Pylons is nice and very adaptable, but I prefer django since it comes with good standards for everything and if you don't like one aspect you can change it rather easily (I've use cheetah for my templating language, for example).

deimos
Nov 30, 2006

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

Ugg boots posted:

So, I'm working on a game for a class, in PyGame, and I had a question about Python:

I have several objects each with a common property (HitRectangle.) I have a collision detection algorithm working fine, but I'd like to have it so it calls a different collision method based on the types of the two collided objects. Since this will be called several times per frame, I'd like it to be as fast as possible, but really I don't know where I want to start.

The only real idea I had was to create a member variable called Type or something for each object, then compare two objects' Type strings and then determine which function to call, but it seems like there should be an easier way.

You can't use type(obj)?

deimos
Nov 30, 2006

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

Mr. Heavy posted:

Is there any really good standard library reference for Python? Compared to Ruby, the official documentation absolutely sucks, and it's really frustrating me because I absolutely adore the Pylons framework and then doing more menial Python stuff in the framework is comparatively painful.

http://effbot.org/librarybook/

I posted it earlier but OP hasn't added it.

deimos
Nov 30, 2006

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

m0nk3yz posted:

It was/is added

I am blind, sorry.


Now more on topic: woop, properties for 2.6 and 3k: http://bugs.python.org/issue1416

deimos
Nov 30, 2006

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

m0nk3yz posted:

Dude, gently caress whitespace. http://timhatch.com/projects/pybraces/

Also, I pre-ordered the django book tonight.

from __future__ import braces

:c00lbert:

I actually had someone argue the whole whitespace thing with me in college. I told him I didn't care and that I much prefer the way whitespace is significant in python. Same guy had some problem with his java code on one of our classes and asked me to check it... yep, he did an if, if, else and had it indented wrong and attributed the else to the wrong if.

deimos fucked around with this message at 04:17 on Nov 14, 2007

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
Has anyone used pyglet yet?

I've been playing around with it and it's awesome, I think I am going to see if I can make a Visual Hub wannabe with it.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
Yes, I know I was the last reply to this thread, but I am currently debating a e/n post because I just got bit by one of python's more annoying "features": all directories are modules. Working on setting up my personal dev server, and goddamnit if I didn't have the hardest time setting up my virtual host with fastcgi.

Who would've thought /home/lighttpd/vhosts/domain.tld/django was a bad loving idea for putting the django projects for my site.

Yep. I just spent about half an hour wondering what the gently caress was wrong.

deimos fucked around with this message at 01:44 on Nov 18, 2007

deimos
Nov 30, 2006

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

bitprophet posted:

Call me stupid, but I don't get exactly what was wrong there? Never used FCGI, FWIW, always mod_python.

Not a problem with fcgi. But it was trying to import stuff in my directory called django, not the actual django stuff in my site-packages.

deimos
Nov 30, 2006

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

m0nk3yz posted:

When Django Apps are served up via mod_python within Apache, the model is wildly different (given apache does use multiple cpus/cores).

Same with FastCGI and WSGI.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
I would personally rewrite:
code:
class gameVars():
 
	# the paddle sub-class
	class paddle():
		x = 0
		y = 0
		w = 128
		h = 16
 
	# the ball sub-class
	class ball():
		x = 0
		y = 0
		vx = 0
		vy = 0
		radius = 8
 
	# the arena sub-class
	class arena():
		w = 512
		h = 640
		score = 0
		lives = 0
		round = 0
		balls = []
as
code:
gameVars = {
	'paddle' : {'x':0,'y':0,'w':128,'h':16 },
	'ball' : {'x':0, 'y': 0,'vx':0,'vy':0, 'radius' : 8},
	'arena' : {'w' : 512,'h' : 640,'score' : 0,'lives' : 0,'round' : 0,'balls' : [] }
}

duck monster posted:

Yup. Thats the magic of python. Dictionarys, lists and tuples. So simple, and yet so expressive. Sure you can do it in other languages, but python makes it so elegant.

Also, Py-game is a really fun library. Aeons ago I wrote a little game that I never finished based on a really spastic take on eve-online (Called something like "goonie lagsplot 2d" or something absurd). Although I never really bothered beyond about 4 or 5 pages of code it was loving fun to write what I wrote, and the prototype was actually kind of fun.

I could see it being very easy to write a 'real' 2D game in it.

What would be *real* cool would be a python version of Delphis old GLScene library. Open GL coding gets really drat cool when its turned into a first class OO library.

Look into pyglet. OpenGL is pretty much a first class citizen. Not to mention a :swoon: of a positional sound library.

deimos fucked around with this message at 02:40 on Nov 21, 2007

deimos
Nov 30, 2006

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

m0nk3yz posted:

The latest edition of Core Python Programming is really good. Covers 2.5 to boot.

I second this, I particularly like Core Python's treatment of variables and memory.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
I use VIM. But as far as IDEs go PyDev is best free, Wing is best commercial.

deimos
Nov 30, 2006

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

Git posted:

I use nano through Cygwin. Yes, I apparently do hate myself.

I think I'm going to try to get used to using PyDev now though.

god, notepad++ is probably 100x better than nano through cygwin.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
Make a manager for entries and use a filter: categories__in=[ list of categories on current entry instance ] and slice it to the first 5, it generates two queries. Actually a manager is not needed for this, but it's the django way.

edit: not sure now, you might have to categories__id__in = [ list of category ids on current entry instance ]

deimos fucked around with this message at 20:22 on Dec 4, 2007

deimos
Nov 30, 2006

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

deimos
Nov 30, 2006

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

LOLLERZ posted:

Very astute. There is a better way to match these though.

Non recursive regexes are not a panacea and a lot of things that are commonplace on regular backtracking regex engines would have to be emulated and would most likely would run several orders of magnitude slower.

If you match a{,30}a{30} instead of that one case which benefits the Thompson method, then you'll get about the same result between the methods. In fact, the Thompson method needs to be modified to emulate the backtracking method.

deimos
Nov 30, 2006

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

Digital Spaghetti posted:

(yes I know Django has it's own Free comments, but it's poo poo)

poo poo? Fairly undocumented perhaps, but they have everything, karma, adaptable moderation, akismet integration, what's poo poo about it?

Digital Spaghetti posted:

Well maybe I'm a bit harsh - but what I mean is it isn't really extensible without having to go in a change some core code as far as I can tell - I want to remove the site field, and add a few other fields in so it's more like wordpress, unless you can tell me otherwise? And I don't see Askimet integration, which is what I am looking for but as you say the docs are pretty poor

Err my bad, akismet integration is not out of the box, you can use signals to pretty much make the comment system do whatever you want.

Unfortunately some of django's best things are often the worst documented.

deimos fucked around with this message at 04:13 on Dec 8, 2007

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
There's also http://code.google.com/p/django-comment-utils/

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
I don't know how old this is, but it references one of my annoyances with python. There's such a thing as TOO much choice.

bitprophet posted:

FWIW when anyone asks "What GUI toolkits should I use with Python?" the answer is almost always "Tkinter, which is kind of old and busted, or wxWidgets, which is the new hotness; and Python bindings exist for most platform-specific GUI related setups out there, such as GTK or Cocoa, if you don't care about cross-platform." Not "See this list of a dozen+ toolkits".

This I know, but I keep having people point out GUI toolkit of the month to me all the time, that's the real annoyance I guess. Or people telling me "hey check out the cool application I made with <obscure toolkit 876213>".

deimos fucked around with this message at 20:12 on Dec 11, 2007

deimos
Nov 30, 2006

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

politicorific posted:

okay I guess I should've used my exact code

this returns this:
code:
('\xd7\x90\xd7\x91\xd7\x93', '\xd7\x90', '\xd7\x91', '\xd7\x93', '', '', '', '', '118', 'intrans', 'lose')
('\xd7\x90\xd7\x91\xd7\x93', '\xd7\x90', '\xd7\x91', '\xd7\x93', '', '', '', '', '91', 'trans', 'lose')
then if I do something like
code:
 z = row
print z
This will assign a single cursor selection to row, print it, then go ahead and assign another cursor selection to row and overwrite it.
How do I store multiple rows to different variables so that python/gadfly isn't overwriting them? The problem isn't the select statement, I'm getting the data I want, I just want all of it - it's the fetchall() statement that I'm having a hard time understand

you just want all the rows? then just assign it, fetchall is a generator.

code:
>>>rows_as_list = list(c.fetchall())
>>>for x in range(len(rows_as_list)):
...   print x
...
('\xd7\x90\xd7\x91\xd7\x93', '\xd7\x90', '\xd7\x91', '\xd7\x93', '', '', '', '', '118', 'intrans', 'lose')
('\xd7\x90\xd7\x91\xd7\x93', '\xd7\x90', '\xd7\x91', '\xd7\x93', '', '', '', '', '91', 'trans', 'lose')
>>>print x[0]
('\xd7\x90\xd7\x91\xd7\x93', '\xd7\x90', '\xd7\x91', '\xd7\x93', '', '', '', '', '118', 'intrans', 'lose')
>>>print x[0][0]
'\xd7\x90\xd7\x91\xd7\x93'

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
So why don't you want to edit *args or **kwargs?

deimos fucked around with this message at 06:12 on Jan 9, 2008

deimos
Nov 30, 2006

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

Lord Uffenham posted:

code:
def dec(f):
    def inner(*a,**k):
        return f(*a,**k)
    inner.func_name = f.func_name
    #setting this in f.func_dict does not work for some reason
    inner.func_dict['clowns'] = 1
    return inner

@dec
def foo():
    print foo.clowns

foo()
It prints 1. Booyah.

Yeah but what happens if you call foo(clowns=20)?

deimos
Nov 30, 2006

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

m0nk3yz posted:

Interesting you should say this now - Someone just posted an excellent Python reading list here: http://www.wordaligned.org/articles/essential-python-reading-list

Ohh and here I thought I was the only one that had this reaction when browsing the library docs:

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
PyRXP is probably your best choice.

deimos
Nov 30, 2006

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

epswing posted:

On the threading module page, why is it
code:
self.value = value = self.value + 1
and not
code:
self.value = self.value + 1
?

Because he's updating the global value at the same time, seems like a convoluted way of doing it since he's returning it too.

ynef posted:

Because they're trying to save an extra line. Both the object specific "value" (self.value) and the global variable "value" are affected, and set to "self.value + 1".

Yeah but he's returning and assigning to value anyways outside the critical section. You might as well return self.value. :iiam:

deimos fucked around with this message at 19:33 on Feb 10, 2008

deimos
Nov 30, 2006

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

epswing posted:

Ok, let me ask this, if
code:
self.value = value = self.value + 1
is changed to
code:
self.value = self.value + 1
and
code:
return value
is changed to
code:
return self.value
am I looking at exactly the same program? Output seems to be the same. Why would they throw in this value variable?

I am pretty sure it might be a remnant from the evolution of the example, ie. a previous version might have just used the global value without the return assignment.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
Hey I was wondering, what way do you guys use of getting a class from a string? I've been doing it in a fairly convoluted way and really think there's an easier way.

deimos
Nov 30, 2006

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

No Safe Word posted:

You mean serialization? There are a couple of ways: the shelve and pickle modules that are built in will do it for you fairly easy and there are a number of other ways as well.

Nah, I am more thinking for settings and class loading. Like storing the name of the class you're supposed to use for a certain task on a settings file as a string then loading the correct class. Right now I use an eval and I really don't like it.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
This is something I threw together last time I needed importing from CSV:

code:
from django.conf import settings
from django.db import transaction

from clients.models import Informacion_Dentista

import csv, codecs, unicodedata, sys
from datetime import datetime

@transaction.commit_manually
def main():
    rc=0
    try:
        print sys.argv[1]
    except:
        transaction.rollback()
        raise
    csvreader = unicode_csv_reader(codecs.open(sys.argv[1], "r", "utf-8"))
    transaction.commit()
    try:
        r = csvreader.next()
        row_names = {}
        x = 0
        for f in r:
            row_names[x] = f
            x = x+1
        row_dict = {}
        for row in csvreader:
            for i in range(x):
                row_dict[row_names[i]] = row[i]
            row_dict['apellido_dentista'] = ''

            e = Informacion_Dentista()
            for k,v in row_dict.iteritems():
                e.__setattr__( k, v )
            e.save()

    except:
        print "Exception caught"
        transaction.rollback()
        print r
        raise
    else:
        transaction.commit()

def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
    # csv.py doesn't do Unicode; encode temporarily as UTF-8:
    csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
                            dialect=dialect, **kwargs)
    for row in csv_reader:
        # decode UTF-8 back to Unicode, cell by cell:
        yield [unicode(cell, 'utf-8') for cell in row]

def utf_8_encoder(unicode_csv_data):
    for line in unicode_csv_data:
        yield line.encode('utf-8')

if __name__ == "__main__":
    main() 
I run it like this:
code:
PYTHONPATH='.' DJANGO_SETTINGS_MODULE=settings python csvimport.py buttes.csv

deimos fucked around with this message at 14:52 on Feb 25, 2008

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
or you can browse django's source and grab SortedDict.

edit:

Habnabit posted:

Oooor you could wrap a sorted around it. for item in sorted(struct): ...

that should be for key in sorted(dict):


because sorted() on a dict only returns the keys

also:

oRenj9 posted:

The ordering is quite consistent for being magical.

...

Edit: I'm surprised this behavior is not discussed in the documentation.

It's consistent, but it differs accross implementations, which is exactly what the docs says.

Python Library Docs posted:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): "pairs = zip(a.values(), a.keys())". The same relationship holds for the iterkeys() and itervalues() methods: "pairs = zip(a.itervalues(), a.iterkeys())" provides the same value for pairs. Another way to create the same list is "pairs = [(v, k) for (k, v) in a.iteritems()]".

deimos fucked around with this message at 15:26 on Feb 28, 2008

deimos
Nov 30, 2006

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

Wedge of Lime posted:

Though they're still having issues, I believe the ordering of dicts is what causes the following lovely bug (I believe):

http://code.djangoproject.com/ticket/4193

http://code.djangoproject.com/ticket/6374

Isn't that because they use regular dicts instead of the sorted alternative? I know that's why they're having some tests fail on PyPy. The tests expect CPython ordering.

deimos
Nov 30, 2006

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

VirtuaSpy posted:

Newbie Python question:
I know there are different ways to read in the CSV file, and I would like to manipulate the resulting input so that it will work with pyChart. pyChart has its own way to read in CSV data using art_data.read_csv('file', '%d,%s:%d'): http://home.gna.org/pychart/doc/module-chart-data.html But it wants a specific format that my CSV file does not have.

...

Thank you for any help in kicking me in the right direction.

Instead of copy/pasting, read the docs, try:
chart_data.read_csv('file','%f,')

heck I think
chart_data.read_csv('file',',')

should work.

deimos
Nov 30, 2006

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

Habnabit posted:

I was trying to use the same variable names:

My bad. But still, it was worth clarifying.

deimos
Nov 30, 2006

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

outlier posted:

Here's something basic, but it might represent a gap in my Python-fu.

I have a bunch of floating point numbers of indeterminate size. Say, 3.02340, 0.8, 0.0051234. Now with the string formatting, it's fairly easy to specify the number of digits before the decimal points and the number of digits after:

'%2f' % x => ['3.023400', '0.800000', '0.005123']

'%0.2f' % x => ['3.02', '0.80', '0.01']

What I'd like to do is something a bit different, show 3 digits precision overall. So it would look like:

['3.02', '0.800', '0.00512']

Any ideas on the most robust way to do this?

You can do this with the decimal module and setting precision to 3 on the context I guess. You're probably best served by casting it to an engineering string.

ed: forgot link

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
So with Sun hiring Leung and Wierzbicki that makes what 3 major companies (Google, Microsoft, Sun) with vested interests in Python? :woop:

deimos
Nov 30, 2006

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

porkface posted:

Yahoo!, NASA

What I love most about Python's current growth rate is that it's almost entirely due to things Python has been doing all along, not just some new flashy framework or idea.

Err yes Yahoo! too, forgot. Who of the big contributors to python development does NASA payroll?

deimos
Nov 30, 2006

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

FrontLine posted:

Does anybody know how/where to get the Python language pack for VS2005?

AFAIK you can't integrate it, instead you get to use: IronPython Studio

deimos
Nov 30, 2006

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

inveratulo posted:

How do I send control characters through either telnetlib or pexpect?

Ok, this is a slight case of RTFM, because pexpect has a sendcontrol()

Adbot
ADBOT LOVES YOU

deimos
Nov 30, 2006

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

inveratulo posted:

hmmm sendcontrol was the first thing I tried actually but I couldn't get it to work. I kept getting an attribute error:
AttributeError: 'spawn' object has no attribute 'sendcontrol'

Should I be creating my connection object differently? This is how I did it:
conn = pexpect.spawn('telnet ' + host)

update your pexpect

  • Locked thread