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
No Safe Word
Feb 26, 2005

Id4ever posted:

I think I've seen all of these in the wild. I prefer the first one, but when I see pros like Mark Summerfield use c) I wonder if there's a good reason to avoid a).
The good reason is they do different things.

For example, using a) you would skip that branch for when x was "", [], or 0.

Adbot
ADBOT LOVES YOU

No Safe Word
Feb 26, 2005

ATLbeer posted:

Anyone know a module that does MIME decoding for email?
Does the one that comes in the standard lib not cut it? Or was it just overlooked?

No Safe Word
Feb 26, 2005

UnNethertrash posted:

It's hard to explain but with the print commands it's pretty clear, if you run it, that the list 'numbers' gets smaller even though I never remove anything from it. It's got to be some stupid little mistake, but I can't seem to figure it out.
That's because:

code:
    numbers2 = numbers
    numbers2.remove(f)
Everything that does this actually removes stuff from numbers as well. Assignment on lists and other complex datatypes pretty much always makes a reference instead of a copy. Luckily, python ships with the copy module to do what you want!

No Safe Word
Feb 26, 2005

chemosh6969 posted:

Looks cool for small stuff.

Works surprisingly well for larger stuff too.

SQLite owns.

No Safe Word
Feb 26, 2005

functional posted:

What does a tuple do that a list won't? Is it useful for anything? (You seem to be able to 'tuple pack' just fine with a list. Why would I switch over?)

http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/

Summary: Tuples are more like "records", and lists are "collections"

No Safe Word
Feb 26, 2005

tripwire posted:

How do you build a list comprehension that would mimic the functionality of going through every gene in the genome and conditionally applying a mutation if random.random() is greater or less than than some threshold value?
I can get as far as
code:
self.genome = [gene + random.gauss(0,1) for gene in self.genome if r() < threshold]
but that obviously won't work because whenever that last if statement is not true a gene will get cut from the genome.
Using a lambda and map I guess?
Don't use a lambda, just use a real function:
code:
def foo(gene):
    if random.random() < threshhold:
        return gene + random.gauss(0, 1)
    else:
        return gene

map(foo, self.genome)
You can even define it inside the function that uses it so that it doesn't pollute the namespace, in fact I'd recommend it.

No Safe Word
Feb 26, 2005

Honestly I forgot you could do the if clause there and not just on the for portion of the list comprehension. That should be fine :)

No Safe Word
Feb 26, 2005

tripwire posted:

Has anyone used the multiprocessing module before? I'm trying to use a pool to split up the work in my mona lisa triangle mover thing but it doesn't look like you can call it from an instance of a class and point to an instance method (it raises a pickle error, 'can't pickle instancemethod' or something like that. Do I have to make it use a global function? Is there some idiom or pattern for doing this?

I haven't, but I know one poster here has it's m0nk3yz, he was like the main guy who wrote that module got it into python

edit: fixed

No Safe Word fucked around with this message at 10:02 on Jan 13, 2009

No Safe Word
Feb 26, 2005

scanlonman posted:

Aha! That got it to work. Thank you so much.

[edit]

How do I get a subclass to also call the parent's init?

super(parent_class, self).__init__()

No Safe Word
Feb 26, 2005

I'm guessing he has a space before "for" and it's giving an indentation error.

No Safe Word
Feb 26, 2005

Phrog posted:

So... what am I doing wrong?

It's evaluating the first line, which specifically waits for user input. So it then waits until it sees the next newline (normally the user would type in their name and hit enter) and once it does it stores that into name.

So I bet if you just typed name you'd see "print 'Hi', name"

No Safe Word
Feb 26, 2005

Captain Lou posted:

I've been told that it's better not to use methods named __like_these__ unless you really have to -- this adapter class seems kinda hacky, is it not?

__getattr__ is a "special method" that is already defined on objects anyway, Benji is just overriding it.

__getattr__ just let's an object know what to do when something uses the dot operator on it, basically.

foo.bar

could be just as easily expressed:

foo.__getattr__('bar')

edit: actually you should never use __foo__ (both preceding and succeeding underscores) for a method name unless you're overriding an existing, but you should also "pretty much never" use __foo either, and should instead just use _foo

No Safe Word fucked around with this message at 16:40 on Apr 8, 2009

No Safe Word
Feb 26, 2005

NightGyr posted:

I installed python 3.0 on this system for some reason, and its for / range() syntax seems to hate me:

code:
>>> for x in range(10):
	print x
	
SyntaxError: invalid syntax (<pyshell#26>, line 2)
What am I missing?

Edit:

gently caress me, it's the print vs. print() syntax.

Go IDLE, highlighting the line that *didn't* have the problem on it to confuse me.

It does say line 2 ... I can't see the highlighting but ...

No Safe Word
Feb 26, 2005

Sylink posted:

So I have an interesting bug.

My programs were working fine until all of a sudden they decide not to find the module they require anymore.

If I move the source files to my desktop lets say they run fine. However, If I run one in the original directory I get an error as if all of the other py files in the directory ran too and they complain the module doesn't exist.

:wtf:

For example:

code:
Traceback (most recent call last):
  File "C:\Documents and Settings\Sylink\Desktop\Py\diggmagic\xml.py", line 1, in <module>
    from digg import *
  File "C:\Documents and Settings\Sylink\Desktop\Py\diggmagic\digg.py", line 14, in <module>
    from xml.dom import minidom
  File "C:\Documents and Settings\Sylink\Desktop\Py\diggmagic\xml.py", line 4, in <module>
    from xml.dom import minidom
ImportError: No module named dom
That is the error I get if I run xml.py, it decides to open other random poo poo then leaves pyc files in the directory.

I get the same poo poo if I run another py file diggtest.py which for some reason decides to call xml.py

code:
Traceback (most recent call last):
  File "C:\Documents and Settings\Sylink\Desktop\Py\diggmagic\xml.py", line 1, in <module>
    from digg import *
  File "C:\Documents and Settings\Sylink\Desktop\Py\diggmagic\digg.py", line 14, in <module>
    from xml.dom import minidom
  File "C:\Documents and Settings\Sylink\Desktop\Py\diggmagic\xml.py", line 4, in <module>
    from xml.dom import minidom
ImportError: No module named dom
This makes no loving sense and is annoying. If I move diggtest.py and my library digg.py to the desktop they run fine. If I open up a new command line and do from xml.dom import minidom the command works

This really is pissing me off. And these files all worked 5 minutes ago and as far as I know nothing changed. This is under python 2.5
Don't name the file xml.py :)

in digg.py, xml.dom will find xml.py in it first and look for a dom module in it, the current directory is searched first in the python path

No Safe Word
Feb 26, 2005

mister_gosh posted:

I have a loop which adds entries to a dictionary like so:

code:
userDictionary[id] = [name,addr]
I then want to cycle through it later on.

What I'm expecting is to iterate through this DICTIONARY, get its LIST value, iterate through the LIST and extract the values based on their index.

Would I be better off with a multi-dimensional list here instead of a dictionary? The following code is just giving me the first and second letter of the name.

code:
for id in userDictionary.keys():
      
    name,addr = "null","null" # do these need to be instantiated?
    for item in userDictionary[id]:
        name = item[0]
        addr = item[1]
    
    print id,'\t',name,'\t',addr
1) no, you don't need to instantiate variables
2) you don't need that inner loop once you have the id, just do:

code:
name, addr = userDictionary[id]
print id,'\t',name,'\t',addr

No Safe Word
Feb 26, 2005

LE posted:

Okay, here is my first stupid newbie python question. Let there be no mistake about it, I am very green with python.

Here's the deal: I am trying to run through this project that shows how python can be used with curses to make some spiffy apps. It looks straightforward enough, and so I make a go at it. In the middle of the page, there is this bit of code:

code:
import curses

myscreen = curses.initscr()

myscreen.border(0)
myscreen.addstr(12, 25, "Python curses in action!")
myscreen.refresh()
myscreen.getch()

curses.endwin()
The tutorial is all "YEAH JUST GO AHEAD AND RUN IT'LL WORK DO IT DO IT DO IT" and so I did! And it bombs out with this:

code:
Traceback (most recent call last):
  File "curses.py", line 1, in <module>
    import curses
  File "~/Python/curses.py", line 3, in <module>
    myscreen = curses.initscr()
AttributeError: 'module' object has no attribute 'initscr'
I've tried running that little thing on three different platforms (Mac OS X, CentOS, & Debian), and they all generate the same error.

I'm thinking that it is something not too difficult to take care of, but I don't understand what is causing it. I can say with total certainty that curses is installed on OS X.

he;lp


Ho ho, I'm going to catch this one first yet again.

:siren: Don't name your file curses.py :siren:

When you do import curses it looks in the current directory first for a file named curses.py and in your case it's finding itself (yes, it can do this) and loading that as the curses module. If you rename your file it won't find something named curses.py in the current directory and it will go ahead and look on the PYTHONPATH for a curses.py to import and it should find the appropriate one.

edit: put in the quote and sirens to hope LE didn't miss this right below me...

No Safe Word fucked around with this message at 02:03 on Apr 28, 2009

No Safe Word
Feb 26, 2005

m0nk3yz posted:

D'oh. So painfully obvious.

Yeah, but obviously not uncommon since the same thing happened a little over a week ago :)

It used to bite me pretty badly when I'd name my C files test.c and just run make test and try and run it.

test is a shell builtin that will get precedence and make test compiles test.c into a binary named test

No Safe Word
Feb 26, 2005

Honestly the best choice is to have it exported to CSV and then just use Python's built-in csv module, but that may or may not be an option.

No Safe Word
Feb 26, 2005

CrazyPanda posted:

can someone recommend me the appropriate module for python to interface with ms access 2007. im very new to programming and databases but i know some sql. i was trying to use MYSQLdb but i dont know how to create the appropriate connection string for a database on my desktop. please let me know if mysqldb is appropriate.

You want some sort of ODBC lib, I forget which one is the best but here's a few:

http://wiki.python.org/moin/ODBC

No Safe Word
Feb 26, 2005

ATLbeer posted:

wow.... i had no idea you could do that...

insanity and very powerful

Only with numpy, as far as I can tell.

No Safe Word
Feb 26, 2005

outlier posted:

Something so obvious that I'm sure there must be an obvious solution that I'm missing: lexicographic sorting in Python.

I have a set of menu options that should be sorted, which look like

Set 1
Set 2
Set 3
...
Set 10
Set 11

And of course the standard Python source is giving me:

Set 1
Set 10
Set 11
Set 2
...

Any favoured solutions?
Actually what Python does is lexicographic sorting, you want "natural sort"

http://code.activestate.com/recipes/285264/

I don't know of any "standard" solution but that was the first hit for "python natural sort" and it looks okay enough :v:

No Safe Word
Feb 26, 2005

CrazyPanda posted:

hi again guys,

can someone tell me why the following expression is incorrect

listr= [[1,2],[1,3]]

newlistr = [lis.append(3) for lis in listr]

i understand the proper way to build the list im intending on is to use

lis + [3] and not lis.append(3)

but why cant i use the property of an object with a list expression? thanks!

and why do i get [none, none] as a result.
Because the result of lis.append is None, always. seq.append is done in-place on that sequence object and returns None.

No Safe Word
Feb 26, 2005

scrabbleship posted:

I am trying to write a python program to manage music and I am thinking about creating a "music library" type mini-database inside of the program. Does anybody know of a good python library that handles this kind of thing or a good approach to this?

Absolutely

No Safe Word
Feb 26, 2005

supster posted:

Is there a good way I can see a summary of changes between Python 2.3 and 2.6? I need to evaluate the effort required to make a script targetted to 2.6 work under 2.3.


2.3 -> 2.4 = http://docs.python.org/whatsnew/2.4.html
2.4 -> 2.5 = http://docs.python.org/whatsnew/2.5.html
2.5 -> 2.6 = http://docs.python.org/whatsnew/2.6.html

No Safe Word
Feb 26, 2005

I've found pdb's postmortem pm() to be pretty handy as well, and you don't even have to instrument your code ahead of time necessarily.

No Safe Word
Feb 26, 2005

Avenging Dentist posted:

Yeah, cuz it's not like the Python standard libraries have completely schizophrenic naming conventions.

Oh hello there

No Safe Word
Feb 26, 2005

Avenging Dentist posted:

This is the problem:


Eugh, green.

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.

No Safe Word
Feb 26, 2005

Baruch Obamawitz posted:

oh what the christ is this

bad python or bad django?

code:
>>> foo = Class.objects.filter(id=3) # there is no Class object stored with this id
>>> foo
[]
>>> foo == []
False

foo is a queryset, it just pretty-prints like a list

just check foo.count() I think

No Safe Word
Feb 26, 2005

deimos posted:

Django protip:

Use manage.py's loaddata for bulk inserts.

This, fixtures rock.

No Safe Word
Feb 26, 2005

Kire posted:

I come back to Python frequently after a short hiatus, only to find I've forgotten everything. Here's a quick newb question: I want to print a sentence that lists objects in a list, without doing "There is a ['first item', 'second item'] and a third item." How can I make it get rid of the [ and ' for the first items?

code:
room_inventory = ['first item', 'second item', 'third item']

print 'There is a %s' % room_inventory[:len(room_inventory)-1]\
+ ' and a %s'% room_inventory[len(room_inventory)-1] + '.'
Also, this is for a list of variable length, anywhere from 0 to many objects.

Two things, you don't need to put the len call in there, [:-1] and [-1] do the same thing to what you want. But the reason it's printing out like that is because you're passing it a list to interpolate and lists that are made into strings look like ['foo', 'bar']. What you want is something more like:

code:
print 'There is a %s and a %s.' % (', '.join(room_inventory[:-1]), room_inventory[-1])
The ', '.join(L) bit basically joins all of the strings in the list with ', ' between each one.

Or if you want to steal a utility we wrote for supybot, we wrote the most terribly named function ever, commaAndify:
code:
def commaAndify(seq, comma=',', And='and'):
    """Given a a sequence, returns an English clause for that sequence.

    I.e., given [1, 2, 3], returns '1, 2, and 3'
    """
    L = list(seq)
    if len(L) == 0:
        return ''
    elif len(L) == 1:
        return ''.join(L) # We need this because it raises TypeError.
    elif len(L) == 2:
        L.insert(1, And)
        return ' '.join(L)
    else:
        L[-1] = '%s %s' % (And, L[-1])
        sep = '%s ' % comma
        return sep.join(L)
And then you can use that:

code:
print 'There is a %s.' % commaAndify(room_inventory)

No Safe Word
Feb 26, 2005

echinopsis posted:

I'm having trouble with the immutable strings.. I'm writing something small and gimmicky, and it relies on changing individual characters in a string.. (many many times over)

I'm struggling to work out how to get around it

code:
new_string = transformation_function(old_string)
new_string = old_string.method()

No Safe Word
Feb 26, 2005

GregNorc posted:

Ah I see.

Why did interpreter thought the error was on line 15 instead of line 13? (Probably would be good for me to know this for future debugging)

Because that's where it thought the parentheses were closed for that one and so it really thought that Card(3,3 was unclosed within the other parentheses.

No Safe Word
Feb 26, 2005

haywire posted:

also, if I create a dictionary like

<snip>

then print it/use it, it seems to be in a completely different order. Any idea why this is?

Dictionaries have no inherent order. There are ordered dictionary implementations if you want, and Python 3.1 actually has such a type in it natively.

No Safe Word
Feb 26, 2005

nbv4 posted:

code:
        a=0
        for chunk in chunks(qs, 1000):
            print "CHUNK----", a
            
            p = Process(target=actor, args=(chunk,))
            p.start()
            p.join()
            
            a += 1

Allow me to blow your mind with:

code:
        for i, chunk in enumerate(chunks(qs, 1000)):
            print "CHUNK----", i
            
            p = Process(target=actor, args=(chunk,))
            p.start()
            p.join()

No Safe Word
Feb 26, 2005

ATLbeer posted:

Django book ( http://www.djangobook.com/ ) is a GREAT resource.

It still can be but even the "new" version there is kinda old.

The regular doc site is pretty amazing in and of itself:
http://docs.djangoproject.com/

No Safe Word
Feb 26, 2005

And just so Stabby and anyone else curious knows, the common python idiom for ditching an unused variable that's being unpacked is:

code:
   want, _, _, alsowant, _ = something.unpack()
if you only want the 1st and 4th elements, for example.

No Safe Word
Feb 26, 2005

MaberMK posted:

code:
list[0:15] = [100] * 15
e: Actually, since you may want to generalize that to an arbitrary range, this would be more robust:

code:
list[x:y] = [value] * len(list[x:y])

Or just list[x:y] = [value] * (y-x) :v:

No Safe Word
Feb 26, 2005

Bottle sorta does but yeah why python 3.x?

Adbot
ADBOT LOVES YOU

No Safe Word
Feb 26, 2005

Mr. Clark2 posted:

stuff
code:
while tries != 100:
    flip
flip here does nothing. Reassign random.randint(1,2) to flip here each time in the loop and it'll work fine

  • Locked thread