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

deimos posted:

You can't use type(obj)?

Really you want to use isinstance (sometimes in conjunction with type), because that handles inheritance better and is just in general more robust.
code:
>>> class A:
...     pass
...
>>> class B(A):
...     pass
...
>>> foo = A()
>>> bar = B()
>>> isinstance(bar, A)
True
>>> isinstance(bar, B)
True
>>> isinstance(foo, A)
True
>>> isinstance(foo, B)
False

Adbot
ADBOT LOVES YOU

No Safe Word
Feb 26, 2005

Digital Spaghetti posted:

Ohh, very handy this thread has come up. I've been looking at Django for a while, and I'm thinking of switching my project from CakePHP to Django - but I must admit I can't find any "nice" tutorials to get me started - Apart from the Django site and book, can anyone recommend any good resources for it for a beginner at Python?

http://code.djangoproject.com/wiki/DjangoResources - this has tons of other links that are more specific
http://blixtra.org/blog/2006/07/17/top-30-django-tutorials-and-articles/ - this is actually on that link but has other unique links

No Safe Word
Feb 26, 2005

SmirkingJack posted:

Is this book you speak of The Definitive Guide to Django: Web Development Done Right or a different one?

Looks like it, based on the publication details (author and publisher). I was hoping they'd go with the same color scheme they use on the website though :smith:

No Safe Word
Feb 26, 2005

For anyone using Django who doesn't regularly read James Bennett's blog, he recently put up a good three-part post on the new forms stuff (which has been in the SVN for a while but isn't in any release yet).
Though if you're a Django user, I'd suggest reading his blog regularly along with Malcolm Tredinnick's blog (though it's less Django-dense)

No Safe Word fucked around with this message at 01:09 on Nov 27, 2007

No Safe Word
Feb 26, 2005

m0nk3yz posted:

If you want an excellent newforms walkthrough, check out the intro to newforms posts on James Bennett's blog:

http://www.b-list.org/weblog/2007/nov/22/newforms/
http://www.b-list.org/weblog/2007/nov/23/newforms/
http://www.b-list.org/weblog/2007/nov/25/newforms/

No Safe Word at the top of this page posted:

For anyone using Django who doesn't regularly read James Bennett's blog, he recently put up a good three-part post on the new forms stuff (which has been in the SVN for a while but isn't in any release yet).
Though if you're a Django user, I'd suggest reading his blog regularly along with Malcolm Tredinnick's blog (though it's less Django-dense)
:psyduck:

No Safe Word
Feb 26, 2005

Put quotes that will hack around it?
code:
        db_table = 'app_prod"."documents'
I mean this is ugly as all get-out, but it might work.

No Safe Word
Feb 26, 2005

I actually half-expected the book release to coincide with the Django 1.0 release, but I have no idea how far away the 1.0 release is, so that may not have been feasible. And in fact, I'm guessing it's probably a little ways away because it'd be a bad idea to release a book and then immediately obsolete it (granted, it'd still be valid for the 0.96 release, but there's a lot of new cool useful stuff in the 1.0 branch).

No Safe Word
Feb 26, 2005

Not to derail but the latest stuff I've been doing at work has been possible thanks to the help of some Wrox books :)

And for Python-related stuff to get somewhat back on track: here's this!

No Safe Word
Feb 26, 2005

To get this back onto the front page where it belongs and to sort of continue the topic at hand, what do people think of the Python ORMs that are out there? I'm mainly a user of the one built into Django, and I think it's pretty awesome (with a few warts but what doesn't have those?). I know some live and die by SQLAlchemy and there are a few others out there which are pretty heavily used as well. Anybody a whiz with several who wants to provide a good comparison of them?

I will say that when I was doing some ASP.NET (ugh) training last week, the instructor was all high on LINQ and talking about how in .NET 3.5 they had just introduced all this cool stuff and wow delayed execution and chained querysets and ooh so neat, which really blew the mind of some of the other folks in the training but I was like "yeah, some journalism major wrote the same thing for Django" (I don't know that Adrian actually wrote that part, but it sounds funnier ... though I didn't actually say it). Not to say LINQ isn't pretty cool (it is), but I just forget how cool some of the stuff we've already got in our pet frameworks/languages already is.

No Safe Word
Feb 26, 2005

From Simon Willison's blog, a public registry of Django users we Django folks should go register at.

No Safe Word
Feb 26, 2005

Since we've got a bit of a Django thing going on, what's the best idea for how to structure templates within a project and its apps? I've been kind of using this structure, but it conflates project and app when I think they ought to be logically separate:

code:
myproject/
  templates/
    main.html
    other_sitewide_template.html
    app1/
      modelname_detail.html
      modelname_list.html
      otherstuff.html
      etc.
    app2/
      modelname_detail.html
      modelname_list.html
      otherstuff.html
      etc.
  app1/
  app2/
Because main/other_sitewide_template obviously really belong at the project level, it makes sense that you'd have them under myproject/templates, but all the stuff under app1/ and app2/ in that folder "feels" like it should belong in myproject/app1/templates/ and myproject/app2/templates/ - is it best to split it up like that and then tell the template loader to search directories in that order? And how does that work with extends?

No Safe Word
Feb 26, 2005

Perhaps we should make a Django megathread, but I thought I'd post this little ditty in here anyway as it can be used outside of Django.

So, for anyone who has played ToME or other roguelikes, you know there are a ton of different monsters, and knowing their characteristics gives you a leg up in the fight. Well, there used to be a ToME monster search page here, but it seems to have gone away. So I wrote a little parser that grabbed that info and put it into a db for a Django web app so I could search on certain criteria looking for monster info.

Well, when I first started building the search page it looked a lot like this:
code:
if request.POST['name']:
    results = results.filter(name__icontains=request.POST['name'])
if request.POST['depth_min']:
    results = results.filter(depth__gte=request.POST['depth_min'])
if request.POST['depth_max']:
    results = results.filter(depth__lte=request.POST['depth_max'])
if request.POST['hp_min']:
    results = results.filter(avg_hp__gte=request.POST['hp_min'])
if request.POST['hp_max']:
    results = results.filter(avg_hp__lte=request.POST['hp_max'])
Which is gross. For one or two fields it would have been fine, but I now have like 40 search criteria on the page and they use the same basic idiom of "if the variable exists in the POST dict, filter on a given field using a specific comparison type with that variable value". So I refactored that to this:

code:
filter_dict = {
        # post var:  (field, compare type)
        'name': ('name', 'icontains'),
        'symbol': ('symbol', 'exact'),
        'depth_min': ('depth', 'gte'),
        'depth_max': ('depth', 'lte'),
        'hp_min': ('avg_hp', 'gte'),
        'hp_max': ('avg_hp', 'lte'),
        # more...
}

        for (post_var, tup) in filter_dict.iteritems():
            if request.POST.has_key(post_var) and request.POST[post_var]:
                kwargs = {'__'.join(tup): request.POST[post_var]}
                results = results.filter(**kwargs)
So now instead of having to add a whole new if branch every time, I can just add in a new entry to the filter_dict with the POST variable name, the DB model field name and the comparison type, and it will work automatically :)

For those a little lost, here's how it (the for loop portion) works:

  • it iterates over the dict, assigning the key to post_var and the tuple of (field name, comparison type) to tup
  • checks to see if the key exists in the dict (has_key), and if it does, makes sure it's not "blank" (the second portion of the and)
  • builds up a temporary one-entry dict called kwargs (short for keyword args), with a key of 'fieldname__comparison' (created by joining the tuple with a '__'), and a value from the POST dict. So, for a filter_dict entry of 'depth_min': ('depth', 'gte'), we would get: {'depth__gte': request.POST['depth_min']}
  • then it filters results using those keyword args, expanded into actual key=value pairs. The ** operator expands dictionaries into key=value pairs. So our previous example would translate to: results.filter(depth__gte=request.POST['depth_min']) (actually it'd translate to whatever the value of that request.POST entry is, but you get the point)

I'm not a huge fan of the whole <fieldname>__<comparison> syntax that Django uses, but in this case it proved extremely useful.

No Safe Word
Feb 26, 2005

SmirkingJack posted:

Yesterday Reddit pointed me to "How not to write Python code" and one of the things that caught my eye was the following:


I am pretty new to this Python thing and it made me realize that I do not know much about coding in a manner consistent with other Python programmers. Could anyone point out examples of common Python techniques ("this is the way we do switch")?

We do list comprehensions instead of accumulating lists in for loops.

Bad:
code:
new_list = []
for item in some_list:
    new_list.append(item.some_method())
Good:
code:
new_list = [item.some_method() for item in some_list]
That's all I can think of right now. Though as a note I take issue with that post title (and I thought the same thing when I saw it on reddit) - because really it only has like 2 things not to do, and 8 others which are "do this".

edit: also note that you can filter in list comprehensions (though the filter function also works in some cases)

code:
filtered_list = [item for item in original_list if some_predicate(item)]

No Safe Word
Feb 26, 2005

Bonus posted:

How exactly is that variable global? Can someone please explain to me? I would have thought `value` is not put in the global namespace when doing
code:
self.value = value = self.value + 1
but in the method's namespace.

If it's declared/initialized in the global namespace, it can be accessed/modified by any method. If it's not, then yes it's local to that method. What you may not have seen is:

code:

value = foo

# loads of other stuff

class moo:
    def our_method(self, whatever):
        self.value = value = self.value + 1
        return value
That sets both the instance's value attribute as well as the globally accessible value variable. No it doesn't! You need the global keyword, I'm dumb!

edit: durr :downs:

No Safe Word fucked around with this message at 21:11 on Feb 11, 2008

No Safe Word
Feb 26, 2005

Bonus posted:

No Safe Word: Umm, could you perhaps provide a working example of how that works?
Here's what my interpreter says:
code:
>>> class Moo:
...   def __init__(self):
...     self.value = 0
...   def incme(self):
...     self.value = value = self.value + 1
...
>>> t = Moo()
>>> t.incme()
>>> value
5
>>> t.value
1
>>> t.incme()
>>> t.value
2
I'm pretty sure that
code:
self.value = value = self.value +1
creates a variable called `value` in the method's namespace that overshades the one in the global.
That's correct - I didn't look at the context source and just went with the one line you had provided. But now that I'm seeing the source I see that there is no global declaration. Yes, you'd need to use global to actually modify the
value and you would indeed be shadowing the global value, but you can access the value that's in the global scope without the global keyword (you just can't modify it and expect the changes to propagate out of scope).

code:
>>> class Foo:
...     def bar(self):
...             print baz
...
>>> baz = 4
>>> f = Foo()
>>> f.bar()
4
>>> baz = 6
>>> f.bar()
6
So, basically that link is dumb :) If the first thing it's doing is assigning to the variable, it inherently loses whatever value it had in the global scope and just becomes a local variable with the same name, shadowing anything that might want to access the global variable.

No Safe Word
Feb 26, 2005

deimos posted:

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.

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.

No Safe Word
Feb 26, 2005

Bonus posted:

Here's a cool thing I've just found out while doing some stuff for school. The zip function works as its own inverse.
Hah, I literally just did something with this 2 days ago. I was goofing off writing some genetic algorithms stuff in Python and I was doing the whole "roulette choice" algorithm (where each item in a population has a "fitness score" and you choose a random item in the population such that the more fit an item in the population is, it has a proportionally higher chance of being chosen), so I had to do something like this:

code:
# we have fitness_list [2, 5, 10, ...], and population ['foo', 'bar', 'baz', ...]
# which are commonly indexed (ie, the fitness of population[0] is fitness_list[0],
# and we want those same two lists back, but sorted in order of most fit to least
fit_pop = zip(fitness_list, population)
# y first because we want it in descending order
fit_pop.sort(lambda x,y: cmp(y[0], x[0])
fitness_list, population = zip(*fit_pop)
Fairly sure that there are better ways of doing the rest of it, and make it so that I wouldn't need this type of logic anyway, but I found the same thing that you did and thought it pretty cool too :)

No Safe Word
Feb 26, 2005

Destroyenator posted:

code:
while a is not 0:
Don't do this. You want !=. Yes, it will work for this case, but in general when comparing a variable and a constant number you want the equality test, not the identity test.

The reason it works for this case is that the python interpreter pre-allocates objects for the first 256 or so small integers as singletons.

Fake edit:
code:
>>> a = 0
>>> i = 0
>>> while a is i:
...     a += 1
...     i += 1
...
>>> a
257
>>> i
257
>>> a is i
False

No Safe Word
Feb 26, 2005

tef posted:

And, of course list=[x for x in "1234"]

And of course not picking variable names that override/shadow builtin functions like list is preferred ;)

No Safe Word
Feb 26, 2005

JoeNotCharles posted:

Fixed your variable name for you.

l = list("1234") is easier and clearer.

Argh, don't do this either :p (I'm sounding like the crotchety old man in this thread). If you want to use a single-letter variable name for a list, use L instead of l. l is a bad variable name in any language because it looks too much like 1 in fixed-width fonts.

No Safe Word
Feb 26, 2005

Anyone used any of the numerous python text parsing libraries out there? I'm playing around with pyparsing and having a bit of a time with it and was wondering: a) are there better options, or b) does anyone know pyparsing well enough that I should post questions here? I don't have anything specific yet, but it might be nice to know who has used what.

No Safe Word
Feb 26, 2005

Habnabit posted:

I like pyparsing the best out of all of the python text parsers I've seen. I'm definitely not the best, but I can try to help you with problems. I've been working with for a little over a year. It's pretty slow, though, so you shouldn't use it if speed is a concern. I use it for lexing wiki pages, and it's fast enough to work with caching, but it definitely wouldn't work if the page was lexed every time it was loaded.

Okay, well I guess this qualifies as a short question and the thread isn't exactly busting with other questions so here goes.

I'm trying to write a stat file parser for TF2 (I guess I'm a statwhore :byewhore: ), but it uses some funky JSON-like syntax that should be easy to write a parser for using pyparsing but I'm having a bitch of a time understanding why some of it doesn't work. Here's a cut-down sample file:

code:
<!-- dmx encoding keyvalues2 1 format dmx 1 -->
"PlayerStats"
{
	"id" "elementid" "076a075f-a605-42d9-a8b1-2478c0f008c5"
	"aClassStats" "element_array" 
	[
		"ClassStats_t"
		{
			"id" "elementid" "ab132a4c-0e10-49c1-8ee4-811b090568a4"
			"accumulated" "RoundStats_t"
			{
				"id" "elementid" "eb9b2473-2189-4dcd-b7b3-c15ff7500d39"
				"iBackstabs" "int" "0"
				"iBuildingsBuilt" "int" "0"
				<snip>
			}
			"comment: classname" "string" "Scout"
			"iNumberOfRounds" "int" "1609"
			"iPlayerClass" "int" "1"
			"max" "RoundStats_t"
			{
				"id" "elementid" "8de50328-cb14-4fc0-b458-f29c0329c8cf"
				"iBackstabs" "int" "0"
				"iBuildingsBuilt" "int" "0"
				"iSentryKills" "int" "0"
				<snip>
			}
		},
		"ClassStats_t"
		{
			"id" "elementid" "fa0703bc-08b8-4964-934b-18bfad54372c"
			"accumulated" "RoundStats_t"
			{
				"id" "elementid" "f3bf5f05-db8d-4542-8c8a-6f2ba43ce307"
				"iBackstabs" "int" "0"
				"iBuildingsBuilt" "int" "0"
				<snip>
			}
			"comment: classname" "string" "Sniper"
			"iNumberOfRounds" "int" "859"
			"iPlayerClass" "int" "2"
			"max" "RoundStats_t"
			{
				"id" "elementid" "178ae1d7-abd1-4e6d-98a3-616f2729c5b3"
				"iBackstabs" "int" "0"
				"iBuildingsBuilt" "int" "0"
				<snip>
			}
		}
	]
	"iTimestamp" "int" "236806956"
	"iVersion" "int" "0"
	"SteamID" "int" "30350757"
}
I <snip>'ed repetitive portions and cut some other stuff for brevity of course.

So, the pseudo-BNF I worked up looks like:

code:
item :=  <name>  <datatype>  <value>
list :=  <name>  [<datatype>]  "["  (<object>,)+  "]"
object := <name>  [<datatype>]  "{" (<item>|<list>)+ "}"
Where name, datatype, and value are really all just double-quoted strings, [] means optional, and + means one or more. So, here's the pyparsing code I came up with:

code:
statComment = htmlComment
statValue = dblQuotedString
statName = dblQuotedString
statDataType = dblQuotedString

statObject = Forward()
statItem = statName + statDataType + statValue
statList = statName + Optional(statDataType) + delimitedList(statObject)
statObject << statName + Optional(statDataType) + \
    Literal("{") + OneOrMore(statItem | statList) + Literal("}")
statFile = statComment + statObject
But when I try and do a statFile.parse on that data I always get:
pyparsing.ParseException: Expected "}" (at char 132), (line:5, col:5), which refers to the line that starts with "aClassStats". It's like the failure is in the OR'ing of the statItem and statList, though I'm going to try parsing each individual line with all the objects and see if it matches where I expect. But if anything is glaringly wrong let me know.

No Safe Word
Feb 26, 2005

Kaluza-Klein posted:

I have a list that I want to sort. The list would look something likee this:
[python]
[['/mnt/Local/laura', 'IMG_0001.JPG', 1207277478.0], ['/mnt/Local/laura', 'IMG_0002.JPG', 1207277490.0], ['/mnt/Local/laura', 'IMG_0006.JPG', 1207277830.0], ['/mnt/Local/laura', 'IMG_0005.JPG', 1207277795.0], ['/mnt/Local/laura', 'IMG_0004.JPG', 1207277782.0]]
[/python]

I want the list sorted by the third value in each item. I know I can do list.sort() with a flat list, but these are lists within lists, and I have no clue how to proceed.

Maybe this is just highlighting my lack of skill with python, but I find the documentation much harder to understand than, for example, php.

code:
In [7]: random.shuffle(L)

In [8]: L
Out[8]:
[['/mnt/Local/laura', 'IMG_0006.JPG', 1207277830.0],
 ['/mnt/Local/laura', 'IMG_0001.JPG', 1207277478.0],
 ['/mnt/Local/laura', 'IMG_0005.JPG', 1207277795.0],
 ['/mnt/Local/laura', 'IMG_0002.JPG', 1207277490.0],
 ['/mnt/Local/laura', 'IMG_0004.JPG', 1207277782.0]]

In [9]: L.sort(lambda x,y: cmp(x[2], y[2]))

In [10]: L
Out[10]:
[['/mnt/Local/laura', 'IMG_0001.JPG', 1207277478.0],
 ['/mnt/Local/laura', 'IMG_0002.JPG', 1207277490.0],
 ['/mnt/Local/laura', 'IMG_0004.JPG', 1207277782.0],
 ['/mnt/Local/laura', 'IMG_0005.JPG', 1207277795.0],
 ['/mnt/Local/laura', 'IMG_0006.JPG', 1207277830.0]]
You can specify a sorting function that takes two arguments and returns -1, 0, 1 for the proper comparison.

Another better example (since sorting these normally produces the same results):

code:
In [11]: L = [(0, 5), (1, 4), (2, 3), (3, 2), (4, 1), (5, 0)]

In [12]: L.sort(lambda x,y: cmp(x[1], y[1]))

In [13]: L
Out[13]: [(5, 0), (4, 1), (3, 2), (2, 3), (1, 4), (0, 5)]

No Safe Word
Feb 26, 2005

Looks like Sun's App Engine/AWS-alike will handle python as well: http://research.sun.com/spotlight/2008/2008-04-09_caroline.html (see the graphic)

:woop:

No Safe Word
Feb 26, 2005

Hero Pussy posted:

I have a really stupid and really basic Python question because I was using string formatting operators and then my brain stopped working and I'm really tired and I can't find where I learned this in my Python book. :(

What is the difference between d and f (or more accurately why is the difference)? Decimal stops when it hits the decimal and floating point displays the whole thing (eg %d of 1234.1928 is 1234, %f of 1234.1928 is 1234.1928), but I can't remember why.

%d is actually for integers. %f is for floats.

http://www.python.org/doc/current/lib/typesseq-strings.html

No Safe Word
Feb 26, 2005

outlier posted:

Simple. But you commonly also see a style where this is done:

code:
class L(list):
   def traverse (self):
      return _traverse (self)

def _traverse (mylist):
      for i in mylist:
         yield i
What's the difference? It seems to me as if these are functionally different. I though that the second (independent) iterator might be thread-safe or allow against multiple simultaneous iterators. Quick experimentation says not. Any ideas?

I've never seen that, and I don't know why you'd do that. It's kind of a useless breaking-out of a utility function. Just keeping the for and yield in-line is more readable to me and it's only marginally longer.

No Safe Word
Feb 26, 2005

bitprophet posted:

I think the problem is you're passing >1 argument to 'print' (which doesn't even seem legal, how are you doing that?).
I thought the same thing and it turns out it isn't.

The language reference confirms it as well as simply trying it in the interpreter.

And I was ready to pass it through a bit of bytecode exploration using the code here, but SyntaxErrors abound.

edit: and for those interested, when you "fix" it using the other way (putting a comma after name instead of using string formatting), it looks like this:

code:
OFFSET INSTRUCTION          OPCODE    ARG  TYPE                  VALUE
    0  LOAD_GLOBAL          (116)       0  GLOBAL VARIABLE       (raw_input)
    3  LOAD_CONST           (100)       1  CONSTANT              ('What is your name?')
    6  CALL_FUNCTION        (131)       1  OTHER                 (1)
    9  POP_TOP              (  1)
   10  LOAD_GLOBAL          (116)       1  GLOBAL VARIABLE       (name)
   13  PRINT_ITEM           ( 71)
   14  LOAD_CONST           (100)       2  CONSTANT              ('is a very stupid name.')
   17  PRINT_ITEM           ( 71)
   18  PRINT_NEWLINE        ( 72)
   19  LOAD_CONST           (100)       0  CONSTANT              (None)
   22  RETURN_VALUE         ( 83)

No Safe Word fucked around with this message at 18:43 on Apr 24, 2008

No Safe Word
Feb 26, 2005

Zedlic posted:

I need to read a string containing ASCII control characters, but Python won't let me. Even if I read it as a raw string it says "SyntaxError: EOF while scanning triple-quoted string".

An example of a string is:
×J^@¯^@^@
^AQU TEXT
.TEXT TIMESTAMP
^BTEXT

Where ^@ is an ASCII NULL, ^A is start of heading and ^B is end of heading.

I'm sure there's an easy way around this but I can't find it. Any help appreciated.

Post the code. The error you've got sounds like not an error with your logic, but with your actual code (syntax :downs: ).

No Safe Word
Feb 26, 2005

karuna posted:

Hey, how do you pass a variable within a URL?

I am using urllib2

code:
urllib2.urlopen('http://www.somewhere.com/some_other_crap<$MYVAR&>')
This isn't working for me at all, i have also tried %MYVAR and ("\<\$"+"MYVAR"+"\$\>")

Any help would be great, thanks

Are you trying to pass in paramters? Or just trying to interpolate the variable name into the string?

The latter is super-simple:
code:
url = 'http://www.somewhere.com/some_other_crap%s' % string_variable
The former is more difficult (though still relatively simple) but doesn't seem like what you want.

quote:

Also i'm having another problem..

I'm trying to generate a xml file.
I can generate an xml file, However the content is hardcoded in the python script.

like so
code:
 #create a <type> element
paragraph2 = xml.createElement("type")
maincard.appendChild(paragraph2)

#Give type text
typeText = xml.createTextNode("Show")
paragraph2.appendChild(typeText)
How should i go about getting the HTML that i scraped using BeauituflSoup from another script and generating an xml file from it?
HTML pretty much is XML (and XHTML absolutely is XML), what do you need to do this for?

No Safe Word
Feb 26, 2005

Mulloy posted:

Well I'm going through this: http://docs.python.org/tut right now, and I'm going to poke around with the stuff in the OP. Anything you can recommend that'd be more specific to the project I described would be awesome, but one step at a time. And yeah, the guy who mentioned python mentioned the google API engine, but they're full at the moment, so I just downloaded the SDK to toy with once I get there.

Thanks!

Edit: Also, retarded question I'm sure, but the tutorial just has me using the command prompt - is there a preferred editor or environment for python for beginners?

IDLE, the bundled editor with the Python distribution isn't bad for beginners, but you should try out all the popular coding editors and pick one :) I won't name my personal preference here for fear of starting up another thread of those, but there are probably some recommendations in the thread.

No Safe Word
Feb 26, 2005

As a note, you can just use list() on a generator expression to get the list, no need to do the comprehension.

But one thing you have to remember about generators is that you basically can only iterate over them once and then they'll just return empty results (and/or raise StopIteration depending on how you use it). If you want to reuse the values to be iterated over a lot, then you should either continually reuse the same generator expression to create it or just store the results in a list if the size is sensible.

No Safe Word
Feb 26, 2005

JoeNotCharles posted:

Yes, that's the problem.
String formatting operations only doing formatting is ... a problem? :confused:

No Safe Word
Feb 26, 2005

Sock on a Fish posted:

I'm trying to decide between Django and TurboGears for a web app. One thing that I definitely don't like about Django is that updating my model requires manually generating and running SQL queries. I've looked at evolution, but I'm scared to use something that's not yet stable in my application.

However, I don't know if the ORM that TurboGears uses suffers from the same problem. I don't find any warnings about it in the TurboGears or SQLObject documentation, but I wanted to ask to be sure. Can I update a model in TurboGears and expect to see those changes in the database?

There's a whole Django thread actually, and I answered a similar question in it, which basically boils down to having django generate a sql dump script with your data in it, recreating the model (drop/recreate), and then re-inserting the data after you've modified the dump appropriately.

If you use SQLite (which is awesome), it unfortunately doesn't support removal of columns from schema anyway, so you'd have to drop the table :(

No Safe Word
Feb 26, 2005

ashgromnies posted:

I'm writing some image manipulation stuff in Python using PIL and was wondering if anyone would review a few basic functions I wrote(I'm a Python n00b).

code:
def getHue(pixel):
	dom = max(pixel, key=lambda a: pixel.get(a))
	dim = min(pixel, key=lambda a: pixel.get(a))
	if dom == dim:
		return 0
	elif dom == 'r':
		return ((60 * (pixel['g'] - pixel['b'])/(pixel.get(dom) - pixel.get(dim))) % 360
	elif dom == 'g':
		return 60 * (pixel['b'] - pixel['r'])/(pixel.get(dom) - pixel.get(dim)) + 120
	else: # max is b
		return 60 * (pixel['r'] - pixel['g'])/(pixel.get(dom) - pixel.get(dim)) + 240
		
def getLight(pixel):
	dom = max(pixel, key=lambda a: pixel.get(a))
	dim = min(pixel, key=lambda a: pixel.get(a))
	maxi = pixel.get(dom)
	mini = pixel.get(dim)
	light = 0.5 * (maxi + mini)
	return light

def getSat(pixel):
	dom = max(pixel, key=lambda a: pixel.get(a))
	dim = min(pixel, key=lambda a: pixel.get(a))
	maxi = pixel.get(dom)
	mini = pixel.get(dim)
	light = getLight(pixel)
	if dom == dim:
		return 0
	elif light <= 0.5:
		return (maxi - mini)/(2 * light)
	elif light > 0.5:
		return (maxi - mini)/(2 - 2 * light)
		
rgbscale = lambda rgb: {'r': (rgb['r'] / 255), 'g': (rgb['g'] / 255), 'b': (rgb['b'] / 255)}
rgb2hsl = lambda rgb: {'h': getHue(rgb), 's': getSat(rgb), 'l': getLight(rgb)}
Basically what I have here is rgbscale, which converts a ([0:255], [0:255], [0:255]) RGB value to ([0:1], [0:1], [0:1]) and rgb2hsl which converts a ([0:1], [0:1], [0:1]) RGB value to a Hue,Saturation,Lightness value.

Anyone have comments on my style or where I'm not being "Pythonish"?

edit: I just realized it makes NO SENSE AT ALL to return a 3-tuple for HSL from a function that expects a dict for RGB. Ergh.

editx2: changed that
Honestly, I'd think the tuple is better. A little less descriptive perhaps, but those 3-tuples are pretty standard within that space (ie, you're basically never going to pass color information as anything other than RGB(A), and HSL is also the standard ordering).

And I think using lambdas on the last bit is a little too "clever", just write the small function that actually does it:
code:
def rgbscale(rgb):
    return {'r': rgb['r'] / 255,
            'g': rgb['g'] / 255,
            'b': rgb['b'] / 255}

def rgb2hsl(rgb):
    return {'h': getHue(rgb),
            's': getSat(rgb),
            'l': getLight(rgb)}
Or convert those to use tuples if appropriate:
code:
def rgbscale(rgb):
    return (rgb[0]/255, rgb[1]/255, rgb[2]/255)

def rgb2hsl(rgb):
    return (getHue(rgb), getSat(rgb), getLight(rgb))

No Safe Word
Feb 26, 2005

Tuples are for collections of heterogeneous types, lists are for collections of homogeneous types.

edit: Quote from GvR

No Safe Word fucked around with this message at 06:49 on May 30, 2008

No Safe Word
Feb 26, 2005

chips posted:

I worked out how to discover the number of arguments of a method/function in Python, but it doesn't seem to have a way to discover the names of the arguments - anyone know if there would be a way to do this? I realize that in many languages, this probably doesn't make sense, since the names of arguments are just labels local to the definition of the function. If anyone has a nice guide on reflection in Python, it'd be appreciated - I could only find some rather obtuse references that led me to find im_func and so on, which I have to admit is slightly easier than PHP5's reflection methods.

You can do it, but it's not for the faint of heart.
code:
>>> def foo(a, b):
...     pass
...
>>> foo.func_code.co_varnames
('a', 'b')
Check out the Internal Types / Code Objects section here: http://www.python.org/doc/current/ref/types.html

I've never really messed with it, but I am marginally familiar with tooling around with func_code stuff because of this little tutorial/link on exploring Python bytecode: http://thermalnoise.wordpress.com/2007/12/30/exploring-python-bytecode/

edit: haha, and right after I made the post I noticed this:
code:
>>> help(foo.func_code)
class code(object)
 |  code(argcount, nlocals, stacksize, flags, codestring, constants, names,
 |        varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]])
 |
 |  Create a code object.  [b][u]Not for the faint of heart.[/u][/b]
edit2: and also some friends pointed out that the inspect module can do this too with the getargspec function. See the inspect page: http://docs.python.org/lib/module-inspect.html

No Safe Word fucked around with this message at 16:28 on Jun 3, 2008

No Safe Word
Feb 26, 2005

Scaevolus posted:

In Python, 0 evaluates to False. (What you want is colorhash.has_key('r'))

Is there really ever a reason to use has_key now that you can just use in? (Honest question, not snarky contrary response)

code:
if 'r' in colorhash and 'g' in colorhash and 'b' in colorhash:
    stuff
versus

code:
if colorhash.has_key('r') and colorhash.has_key('g') and colorhash.has_key('b'):
    stuff

No Safe Word
Feb 26, 2005

ATLbeer posted:

Can someone show me the Python docs on the *array, **array information? I know what it does but, I've never actually seen the docs for it. It's also hard to google "python *" :(

http://python.org/doc/current/ref/calls.html

No Safe Word
Feb 26, 2005

inveratulo posted:

Okay so I need to create and use a multi-dimensional array of unknown size.
To create, I am doing:
code:
myArray = [[]]
But I am not sure how to append my data to this structure?

Depends on what you want to do. If you're going to be doing math-like stuff, save yourself a headache and just start with NumPy from the get-go:
http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html

Otherwise, you can just start with a list, insert/append a new list, and so on.
code:
In [1]: myArray = []

In [2]: myArray.append([1,2,3])

In [3]: myArray.append([1,3,5])

In [4]: myArray.append([2,5,7])

In [5]: myArray
Out[5]: [[1, 2, 3], [1, 3, 5], [2, 5, 7]]

In [6]: myArray[2]
Out[6]: [2, 5, 7]

In [7]: myArray[1][1]
Out[7]: 3

Adbot
ADBOT LOVES YOU

No Safe Word
Feb 26, 2005

JoeNotCharles posted:

Aside, does anyone know a good site listing the complexity guarantees of common operations for common data types? I should know this off by heart but I always end up having to look it up...
Something like the table on these pages:

http://www.cplusplus.com/reference/stl/

(which are the STL container operations' complexities)

for Python would be awesome.

  • Locked thread