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
bitprophet
Jul 22, 2004
Taco Defender

deimos posted:

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.

Not entirely true. Sure, if you don't use its ORM you lose the generic views and the admin (basically, the nice "extras") but it's entirely possible to just use its URL mapping + view functions + templating and use e.g. SQLAlchemy to populate the template contexts.

And, yea, the ORM is pretty flexible in general, it's possible to tweak most aspects of the generated SQL with a ".extra()" method on the query objects (e.g. adding WHERE clauses), and as you said, you can use 100% raw SQL alongside the ORM if those don't do the trick.

Adbot
ADBOT LOVES YOU

bitprophet
Jul 22, 2004
Taco Defender

Triple Tech posted:

What's the Python community like? Do you guys really hate Perl? And have you ever heard of or used SQL Alchemy?

I went to one Python Users Group meeting and everyone had something nasty to say about Perl. And the presenter there was my former boss, creator of SQL Alchemy.

That wasn't in New York, was it?

We don't "hate" anybody, generally - most of us like Python because it's awesome, rather than actively disliking other languages. That said, I've noticed a fair number of Pythonistas are former Perl monks, and that means those folks are generally very aware of the difference between Perl's "executable line noise" (exaggerated or no, it's still got a reputation for being messy) and Python's emphasis on clean, readable syntax. If they're still with Python now that means they prefer the latter over the former, and thus will gripe about the "bad old days" when they had to try and read their 6-month-old Perl scripts.

In general I like the Python community because it has an overall positive attitude, and there are a lot of smart people who ended up here after spending time solving problems with other languages, and are thus very happy to be able to focus exclusively on doing that instead of wrestling with syntax or whatnot. There's a lot of emphasis on doing things "the right way" and that tends to pervade the community, from what little I've seen.

Honestly, though, I don't interact with the community as much as I should, and definitely ought to add more blogs to my RSS feed :) I also don't have much experience in other communities, period, and can't contrast it too much with others outside of "PHP has lots of newbies", "Perl has lots of sysadmins", "Ruby has lots of arrogant twats*", etc.

* OK, only some of them. I work in a half-Rails shop and most of the devs here are pretty down to earth.

bitprophet
Jul 22, 2004
Taco Defender
Look, between that whitespace bullshit and this inability to handle threading natively, I don't see how anyone can consider Python anything but a toy language :colbert:


...on a more serious note, to anyone else who may have been using Python for a few years now and taking it for granted: go write nothing but PHP for a month or two. You'll stop taking it for granted real quick...:gonk:

Also, the official Django book is done! Should be on shelves by mid/late December, if not earlier, I'm told :)

bitprophet
Jul 22, 2004
Taco Defender

m0nk3yz posted:

Also, I pre-ordered the django book tonight.

I pre-ordered it the day pre-orders were announced, which at this point must have been at least a year+ ago. Got like a half-dozen notices from Amazon since then about its release date being pushed back. But no more!

bitprophet
Jul 22, 2004
Taco Defender

SmirkingJack posted:

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

Yup, that's the one. Adrian and Jacob. I think the color scheme is because it's part of a technical series by the publisher, I recognize it from other books. A Django book with the Django website colors would rock, though.

bitprophet
Jul 22, 2004
Taco Defender
Call me stupid, but I don't get exactly what was wrong there? Never used FCGI, FWIW, always mod_python.

vvv Gotcha. That's not really a directory-as-module issue (since it should only treat directories as modules if they contain a '__init__.py' file) but more a pathing issue - the local path overrides site-packages if there's a collision, as you discovered.

bitprophet fucked around with this message at 18:27 on Nov 18, 2007

bitprophet
Jul 22, 2004
Taco Defender

deimos posted:

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.

Eh, that's generic programming/open source for you, has nothing to do with Python itself IMO. Coders have been reinventing the wheel/working on parallel solutions to the same problem, forever.

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".

bitprophet
Jul 22, 2004
Taco Defender
The book has had problems getting out on time, and so has the 1.0 release, so I'm guessing it was released when it was simply because "oh god we're finally done".

There's a WROX book out that includes Django in its content and was published like a month ago, but it's WROX, I'm told their quality is Not So Great (never read any myself). There are also at least two or three other Django books that will be released over the next ~6 months or so :)

bitprophet
Jul 22, 2004
Taco Defender
You need to understand SQL more. SQL result sets are explicitly unordered unless you specify an ORDER BY clause. So you should never, ever assume any sort of order in such a result unless you're using ORDER BY.

So change your SELECT statement to something like
code:
SELECT * FROM table ORDER BY colname
and then it will be consistent every time you call it.

bitprophet
Jul 22, 2004
Taco Defender
I too am basically defined as a "Django ORM user". I used some SQLObject before I found Django but hardly remember it, and was at an NYCPython meetup where the author of SQLAlchemy gave a little talk about that, looks pretty neat, and can probably do "more" than Django's ORM at the expense of not being quite as concise. However I haven't actually used it yet so hard to say for sure.

I'm currently debugging a PHP project which is basically the purest form of PHP you can find, namely absolutely mind-boggling horrible :psyduck:-inducing shite. Including your standard raw SQL queries up the ying-yang, building them in various ways, with plenty of near-breakage and probably a million potential injection exploits.

Makes me appreciate ORMs and Python all the more :(

bitprophet
Jul 22, 2004
Taco Defender
No idea how I missed that, thanks a lot! :) (edit: Oh, I didn't miss it, I just happened to see your post before checking my feed reader :v:) Neat site, despite getting a couple 500 errors trying to browse, and the screwed up tab order on the signup form.

I envy those of you going to Pycon, I don't have the vacation time for it this year since I had to borrow for some important stuff that went down last year. Oh well. Hope you have fun!


It's been made public as of a week ago (in Michael Trier's Jan 11th podcast), so I might as well toot the horn here: I and two other gents are working on a Django book :) it's been interesting so far and I hope we can get it out soonish and make it high quality as well.

The framework is a moving target (for example, the method of generating forms from models in newforms changed without my noticing it about a month or so ago, and newforms itself is still relatively new and exciting...) which makes things difficult, but at least ours will be more up-to-date than the Apress book. Which is still a great book - anyone using Django should definitely grab a copy.

bitprophet fucked around with this message at 06:07 on Jan 23, 2008

bitprophet
Jul 22, 2004
Taco Defender

Bonus posted:

bitprophet: Yo that's way cool! Will it be aimed at intermediate or beginner users? If you ever need to test the book out on someone or something like that, let me know!

It's aimed at beginning and intermediate both, basically. We're providing a command line intro appendix, a chapter on Python (which is somewhat tailored for how it's used in Django, obviously) written by the author of Core Python, and some high level material on what Web development is all about from a backend perspective. So enough for a PHP dev to be able to pick up our book and finish it knowing how to use Django and use it well (not to mention that some of this will be of interest to people coming from the Java web world, Rails devs, and so forth).

However, that's only part of the book, with the rest being just info about how Django works, best practices, example applications, and generally an attempt to cover the real-world applicable knowledge that the Apress book might not go into.

bitprophet
Jul 22, 2004
Taco Defender
As implied in your posts, there's two main template loaders - one global templates dir, or per-app templates dirs. The per-app setup is obviously preferable on the face of things because it means your apps are wholly self-contained; unfortunately it suffers from an odd problem which I don't know the answer to, but might investigate sometime as it's one of Django's biggest warts right now IMHO.

The root of the issue is how we reference templates: relatively ("appname/templatename"), not absolutely ("/path/to/templatedir/templatename"). The root "namespace" that determines how templates are found depends on the loader used, a simple single folder in the global setup, or a concatenation of all the per-app folders in that scenario (technically, it looks in each app dir in order, but the effective result is the same).

It's this implicit concatenation which is the problem - it means your template names must be 100% unique in order to be picked up correctly. If you have app1 and app2 with per-app template folders, and they both contain "index.html", then a template loader call to "index.html" will pick up the template whose app is listed first in your settings.py. So app2 is poo poo out of luck.

You can get around this by adding a level of depth to your folders, i.e. "$myproject/app1/templates/app1/index.html", but then you're typing that extra "app1" all over the goddamn place and it just looks stupid (like how Django used to be about 2-3 years ago, before magic-removal reorganized things to be a lot more efficient).

Or you can play policeman with your template names and make sure every app uses 100% unique names for all its templates, which is equally irritating/stupid.

:words: Hope that got the point across w/o being too verbose.

If it wasn't obvious, I use the normal global-template-dir loader, with app subdirectories. It's sane, and in my case it's often necessary anyway because my projects tend to be very intermingled with lots of cross-referencing and shared templating, making the 'app' distinction largely just a way of organizing the models and view functions and less a collection of standalone applications.

EDIT: I just scoured the docs, wiki and djangosnippets.org and nobody seems to have attacked this problem. There's a ticket in the tickets section (sadly a search for app_directories, the name of the loader in question, turns up hundreds of tickets and I was only able to search through the first, like, 200 before I got sick of it :D) wherein someone asked for a change making the current app take precedence when using that loader.

It was rejected largely because that behavior isn't ideal - you often want to include either other app's templates, or global templates, and that's not possible with such a loader. Malcolm also rejected the idea of making a third standard template loader implementing that behavior, which I can understand - they really don't like bogging down the core system with extra stuff unless it's absolutely necessary.

However, I think if the problem can be solved with an extra loader, it would end up being used fairly often, which is why I'm surprised one doesn't exist on djangosnippets - I might try making one just to see.

bitprophet fucked around with this message at 02:57 on Jan 24, 2008

bitprophet
Jul 22, 2004
Taco Defender

cLin posted:

As a person who has learned C++ and PHP, how easy is Python to get into? Pros and cons versus PHP? Figured I'd ask in here since it doesn't really warrant its own thread.

It's very easy to get into, and is generally better than PHP in every way save for not being ubiquitous on shared Web hosting environments like PHP is. I say this as someone who's been paid to write both PHP and Python and is currently paid to do...both :psyduck:

My background pre-Python was Java, VB and PHP and I absolutely fell in love with Python for various reasons. Largely it's just very close to my idea of an ideal language - the syntax is incredible, being both clean and very powerful/concise; the library support is great; the philosophy behind it is well thought out for the most part; the community is full of experienced, intelligent and pragmatic coders from every programming background you could imagine; I could go on.

Comparing to PHP, one of its largest strengths is that it's generally very consistent and clean, where PHP is one huge ugly namespace with inconsistent function names and/or argument specifications.

In addition, PHP's type system is such that it's extremely easy to make mistakes that are difficult to debug (e.g. the implicit cast of a string to an int during some math on line 10 is causing tax to not be applied on line 257, but without any error messages of any sort cropping up) and more explicit languages like Python avoid that almost entirely.

bitprophet
Jul 22, 2004
Taco Defender

cLin posted:

Wow, sounds like something I'd like to learn. What books do you python developers recommend? Something with examples since I learn best with it. How does a program work anyways? I know for PHP you can just write the code into the php file and execute it (printing hello world in index.php and going to index.php), but I never seen any websites with anything that'll indicate it runs off python code.

edit: oh yea, main reason I am interested in it cause I noticed for sites like codegolf.com where programmers from many languages compete for shortest code, python is usually way shorter than php with perl leading as the smallest amount of coding.

Python has no explicit compilation step like C++, it's interpreted, meaning it's closer to Perl or shell scripting - you typically either write a source file and tell the interpreter to run it, or you just enter the interpreter yourself and execute code in there. It can also be run in a Web server environment like PHP typically is, but most people do that via a Web framework (Django, TurboGears, Pylons, etc) as opposed to random scripts running at e.g. https://www.mysite.com/myscript.py.

That's why you never see sites looking like they run on Python - the frameworks mentioned tend to favor clean URLs (e.g. https://www.mysite.com/section/subsection/location/) and not URLs that look like filenames :) (In such a situation, there isn't technically one script getting called at that URL - it goes to a URL dispatch function which decides what code to execute/what template to render/etc)

CodeGolf is kind of silly but does serve as a metric for how concise/powerful a language is. Python generally gets high marks in that department due to a combination of factors. For example, list comprehensions make iterative tasks really easy/simple, like here where I have a list of dicts (associative arrays in PHP) with peoples' names and ages and I want a list of just the ages:

code:
people = [{'name': 'Bob', 'age': 15}, {'name': 'Susy', 'age': 32}, 
    {'name': Henry', 'age': 26}]
ages = [x['age'] for x in people]
Compare to the equivalent PHP:

code:
$people = array(array('name' => 'Bob, 'age' => 15), 
    array('name' => 'Susy','age' => 32), 
    array('name' => 'Henry', 'age' => 26)
);
$ages = array();
foreach($people as $person) {
    $ages[] = $person['age'];
}
Another notable feature of Python's syntax is that everything is expression-based, like building blocks in a way, so things can be easily composed. Imagine a function called getPeople that returns the 'people' list/array from the previous example; and imagine wanting to call that function and do something with its return value. In PHP you have to break this up into at least two statements:

code:
$retval = getPeople($arg1,$arg2);
$first_person = $retval[0];
In Python you just make one statement:

code:
first_person = getPeople(arg1,arg2)[0]
This becomes even more useful when (not if; this comes up a lot!) you need to grab stuff that's nested pretty deep. Imagine our 'people' above are actually objects instead of dicts, and we want to call a person's, say, 'listOfFriends()' method - which returns more People - and grab the first friend's age. My PHP object syntax is hazy (been working with very non-OO PHP), but I think it would look like this:

code:
$retval = getPeople($arg1,$arg2);
$first_person = $retval[0];
$firsts_friends = $first_person->listOfFriends();
$ffa = $firsts_friends[0]['age'];
Python? Still one line, and still very readable and obvious.

code:
ffa = getPeople(arg1,arg2)[0].listOfFriends()[0]['age']
I kinda just spent way too long writing all that :v: but hopefully it's a good illustration of the power of the language. Apologies if I've misrepresented anything in PHP, I've been working with PHP4 for the last 6 months (after a 3 year break from that language) and distinctly remember composition simply not being possible.

Also, while it appears trivial, note Python's lack of semicolons and braces for expression/block delimiters. It saves a lot of typing over time, and is one less thing to be thinking about / screwing up. And no, using indents to determine blocks is not a big deal, despite lots of people saying it turns them off. If you indent your PHP/Java/C++/whatever in a readable fashion, you're already doing it the Python way.

bitprophet fucked around with this message at 05:39 on Feb 15, 2008

bitprophet
Jul 22, 2004
Taco Defender
Er. Hate to be all RTFM on you but did you look at the documentation? Go to the Django documentation page and it's the 5th line down under the Reference header :)

Granted, comprehensively testing web apps is a bit tougher because of their nature, but you can still get a lot done with a simple set of unit tests testing object creation/editing/deletion, making sure all your URLs result in HTTP 200s and aren't breaking, and putting doctests on any non-builtin model methods you write (e.g. if you do something like get_sum_of_child_numbers(), do a doctest to ensure it works correctly). So on and so forth.

bitprophet
Jul 22, 2004
Taco Defender

SmirkingJack posted:

I thought part of Django's charm was that it didn't force you to use anything you didn't want to. So if you wanted to use a different db layer/ORM then you could.

Yup. This is a major misunderstanding about Django; it is loosely coupled by design. Yes, you lose the contrib apps (admin, auth, etc) and generic views, but it still works perfectly fine in terms of URL dispatch, view functions and template rendering.

Now, given that the contrib stuff is a large part of what people like about Django, it's fair to say that you prefer how TG or Pylons does things at that level (when Django is "only" the URL dispatch + views + templates) but it's entirely possible to use Django sans its ORM, and it's designed that way on purpose.

bitprophet
Jul 22, 2004
Taco Defender

lilbean posted:

I've been trying to find this too (basically the equivalent of a lot of the Java reflection API).

Can you guys elaborate more on the background of wanting to do things this way / what problem needs solving? On the face of it it sounds sort of icky / un-Pythonic, to me, but I don't want to be judgemental until I know more.

I can say that generally when I hear someone wanting to make code-loading decisions based on a string, the answer is either getattr()/dict key access, or __import__().

Edit: vvv That works too - globals() and locals() exist for a reason. Just try not to alter them, I think that's generally a big no-no :)

bitprophet fucked around with this message at 00:00 on Feb 16, 2008

bitprophet
Jul 22, 2004
Taco Defender

trashmatic posted:

If you mean that you can't call 'continue' inside a function and expect it to abort the loop it was called from... well, yes. You can't do that.

I think this is coming in Python 3 though, could swear I read that somewhere :) Not that it helps the poster any, of course. I'd second everything you said, at any rate.

EDIT: reading comprehension :downs: Can't do what you said, but Python3000 is adding multi-level continue statements, I think - i.e. if you're 3 nested for loops deep, you'd be able to have a single continue that says to break out of all 3.

Regarding the original assertion, yea, it's not possible for a function to have any real idea about the state of things when it's being called - it is solely concerned with taking input and giving output, and that's it.

bitprophet fucked around with this message at 16:59 on Feb 25, 2008

bitprophet
Jul 22, 2004
Taco Defender
Thanks for the correction, goes to show that I don't exactly follow the mailing list very carefully :haw:

bitprophet
Jul 22, 2004
Taco Defender
You probably want the subprocess module, check docs.python.org for your Python version and you'll see it in the listing (the docs.python.org/lib/ page + your browser's quicksearch function = very easy access to almost all of the Python docs).

It's a newer replacement for older stuff such as the popen module, which is what used to provide the functionality you're looking for - the ability to define the stdin/stdout/stderr pipes to the command in question.

You can use it like this (going from memory here, don't copy/paste this, look at the docs):

code:
from subprocess import Popen, PIPE

command = Popen("/path/to/binary -args",use_shell=True,stdin=PIPE,stdout=PIPE)
command.stdin.write("text to input to the command")
print command.stdout.read() # prints the output of the command
That's equivalent to, in the shell,

code:
$ echo "text to input to the command" | /path/to/binary -args

bitprophet
Jul 22, 2004
Taco Defender

JoeNotCharles posted:

Subprocess is awesome - it saved my rear end just yesterday. I was spawning a DOS program that insisted on asking "Do you really want to modify this file (Y/N)?" for every file it updated, on thousands of files. I thought it was going to be a huge pain in the rear end making it send a Y over and over, but it turns out "Subprocess(...).communicate("Y")" was all I needed. If it didn't modify a file, it throws the Y away.

Unix has had a "yes" binary for probably a very long time; with no arguments it simply sends 'y' + a carriage return, over and over, to stdout. Very useful for piping to commands like the one you were using, which are retarded enough to ask Y/N type questions without accepting a --force sort of option.

You can also give "yes" any string as an argument and it'll repeat that instead. In the more juvenile-minded this typically causes behavior such as gleefully typing "yes gently caress" upon discovering the program for the first time.

bitprophet
Jul 22, 2004
Taco Defender

Moof Strydar posted:

code:
(c > 0x99) and '0' or ''

Just want to pop in with the usual "be really careful with this tactic" warning, it's really easy to make a stupid mistake like the following:

code:
(c <= 0x99) and '' or '0'
Which would appear to be equivalent to the quoted example, but isn't, because it will always return '0' (because "<anything> and ''" will always evaluate to False due to the empty string).

bitprophet
Jul 22, 2004
Taco Defender

deimos posted:

Not if you're using a good coding font. Fonts should not affect how you code.

Except for the myriad of places that code is seen outside of your preferred editor, such as on pastebin websites. It's silly to do things (or rather, to not do them) which require a particular editor/font choice/keyboard layout/etc, when it's just as easy to do the right thing which won't break everywhere else.

bitprophet
Jul 22, 2004
Taco Defender

PrinceofLowLight posted:

print name "is a very stupid name."

I think the problem is you're passing >1 argument to 'print' (which doesn't even seem legal, how are you doing that?). Try this:

code:
print "%s is a very stupid name." % name

bitprophet
Jul 22, 2004
Taco Defender

No Safe Word posted:

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.

Well, if you put a comma or a plus sign, of course it works. His code was literally:

code:
print name "is a very stupid name."
which is incorrect:

code:
Python 2.5.1 (r251:54863, Oct  5 2007, 13:50:07) 
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> name = "Foo"
>>> print name "is not Bar"
  File "<stdin>", line 1
    print name "is not Bar"
                          ^
SyntaxError: invalid syntax
Pedantry: only slightly less dickish when it concerns programming :downs:

EDIT: anyway, to double-check whether raw_input sneaks in newlines, it doesn't seem to:

code:
Python 2.5.1 (r251:54863, Oct  5 2007, 13:50:07) 
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> name = raw_input("What is your name?")
What is your name?foo
>>> print name, "is a very stupid name"
foo is a very stupid name
>>>

bitprophet
Jul 22, 2004
Taco Defender
code:
[email]jeff@jeff.loca[/email]l:~ $ ipython 

In [1]: sum([int(x) for x in str(1234567890)])
Out[1]: 45
sum() does what you'd think, it sums a list, e.g. sum([1,2,3]) = 6. So that's how you sum up a bunch of numbers.

Strings in Python are actually sequences, meaning they're very list-like and can be iterated over just like a list, with for loops and etc. So str(some_integer) is how you get all the digits of a given integer, as a sequence.

Of course, you then have to call int() on the individual list items to get them back into integers, otherwise it's rather difficult to sum them :) Python will not automagically let you do things like 1 + "1" like PHP might do. This is a good thing! PHP's way of doing things leads to horribly hard to find bugs, and promotes sloppiness.

Finally, you can make a one-line equivalent to a for loop with a list comprehension, namely [expression for item in sequence] where expression is just something that returns a value, item is your loop variable name, and sequence is some sort of sequence - a list, a string, etc, or some expression evaluating to one.

Putting it all together does exactly what you seem to be asking for...hope it makes sense :)

bitprophet
Jul 22, 2004
Taco Defender
I'm quite aware of generator expressions, but I've been doing Python since before they existed, and it's very hard to change that particular habit I guess v:shobon:v You're right that they are generally superior to list comps.

bitprophet
Jul 22, 2004
Taco Defender
Why those two instead of e.g.
code:
print "%d" % i
or
code:
print "%d % (i+1)
? Granted that %(dictkey)d is useful in more complex scenarios, but given your actual example, using that format and locals() (which seems kinda unPythonic to me, much less explicit than making an anonymous dict after the % operator) seems like overkill.

EDIT: I guess this is what you meant by 'positional' (I just tend to think of it as "normal" :downs:), but that still doesn't quite answer the question of what's wrong with performing the +1 expression on the right hand side of the %.

bitprophet fucked around with this message at 17:50 on May 21, 2008

bitprophet
Jul 22, 2004
Taco Defender
I don't work with handmade iterators much, but I believe what's happening is this:

1. You execute the expression for i in <a Squares object>:.
2. for loops perform iteration on the object following the in keyword.
3. An object can be iterated over if it defines the __iter__() method (__foo__() methods are generally used to implement language behaviors; for example you can have your class implement __lt__() (less than) in order for them to be used with the < operator).
4. Python sees your Squares object being used in a for loop and tries iterating over it, which means calling your Squares object's __iter__() method.
5. The output of that __iter__() method needs to be an iterator, which in Python is defined as anything that implements next(). In your case, since Squares implements next() itself, your __iter__() just returns self.
6. Finally, the for loop keeps calling your Squares object's next() method until it raises StopIteration (essentially using the exception as a signal that the iterator's all used up) and then exits.

The reason it's a bit confusing is because Python wants to give objects the option to return something else as "the iterator" when their __iter__() method is called. For example, your class might implement an internal data object which is the real iterator, like a list or something, and you would then return that. In your case, there's no need for that, so Squares just implements the iterator API itself and returns self.

This happens fairly often in Python; for really simple cases things seem to have an extra step or two, but it's set up that way to make things much more flexible overall.

bitprophet fucked around with this message at 05:19 on Jun 17, 2008

bitprophet
Jul 22, 2004
Taco Defender

trutch posted:

Thanks for the help. I've created a dictionary with key (DATE,MESSAGE) and values (1#count integer,MESSAGE). If the DATE and MESSAGE match a key that is currently in the dictionary, I add 1 to the count integer. Otherwise it creates a new key and value.

I am having problems getting the integer count to work. It seems to be filtering out duplicate entries but the count isn't updating.

code:
rxinput = re.compile(rawstr)
for line in InputFile:
         for input in rxinput.finditer(line):
                 DATE = (input.group(1))
                 MESSAGE = (input.group(2))
                 if (DATE,MESSAGE) in dict.keys():
                         dict[(DATE,MESSAGE)][0]+=1
                         print dict[(DATE,MESSAGE)][0]
                         break
                 else:
                         dict[(DATE,MESSAGE)]=[1,MESSAGE]
Full Source here

Don't call your dict "dict", call it something else, as "dict" is the builtin word for the dictionary type. It's probably not what's causing your problem, but it could definitely cause issues, so don't do it :) same for "str" and so on.

Otherwise I don't see anything obviously wrong, but I haven't gone over it with a fine-toothed comb or anything.

bitprophet
Jul 22, 2004
Taco Defender
That's actually been known for a while, but yea, it's definitely cool. If I wasn't a Mac fag with an iPhone I likely would own one of those Python capable Nokias by now :)

I actually started learning Python for a course where we wrote wirelessly enabled apps for the Sharp Zaurus running a micro-Linux. Not quite as cramped an environment as a cell phone, but close. It was fun.

bitprophet
Jul 22, 2004
Taco Defender
Cairo is often a good choice there. I haven't used a lot of such tools but it was not that difficult to use when I tried and it's cross platform and flexible in terms of what you can draw with it.

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.

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 * :)

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.

bitprophet
Jul 22, 2004
Taco Defender

Centipeed posted:

I want to learn Python by making a simple address/phone book application.

In terms of the data structure, is it possible to define an entry in the phone book as a class, and then simply store those entries (Of class Entry, for example) in a list? Would that allow me to add/delete the entries and whatnot?

Depends on what sort of persistence you want. If you're talking about a trying-stuff-out demo app where you don't actually care about the data sticking around, then sure -- lists can hold any object, and class instances are of course objects like anything else. However, once your program stops running, your list will obviously disappear.

If you wanted to keep the data on disk somewhere, the typical method is to use a SQL database, the simplest such being SQLite (which stores stuff in simple files, as opposed to the heavyweights which are full blown servers) -- Python 2.5 has a built-in SQLite library so all you'd need is to install the SQLite binaries and you're all set.

Edit: Fix retarded typo.

bitprophet fucked around with this message at 00:27 on Aug 14, 2008

bitprophet
Jul 22, 2004
Taco Defender

Centipeed posted:

For this exercise, can't I just store the list in a text file with simple markup? A database seems like overkill, even it is is only SQLite.

What do you mean by "simple markup"? I suppose you could use "<whatever> separate values" (comma, tab, pipe, whatever) but then you need to translate back and forth every time you save.

And, yea, SQL is a bit of overkill; I did say "the typical method", not "the only method" ;) I think the best middle-of-the-road approach would be to use the pickle module, which lets you store Python objects in strings (and thus in files).

I probably should have mentioned that first, honestly, but I'm too used to thinking of "real" applications, for which stuff like pickle is almost never a good idea (unless your data sets are very small AND you really want to work with Python objects instead of SQL or an ORM).

bitprophet
Jul 22, 2004
Taco Defender
I'd guess there would be something in the os module (here, probably os.path. os is laid out kind of odd, in that os.path gets its own doc section, but read everything you can find about those 1 1/2 modules and hopefully you'll find something.

Failing that, look in the general stdlib directory, there's a ton other libraries, including platform-specific ones, one of those may have one as well (although then you would, of course, be tied to one specific platform).

EDIT: goddammit why can't the [ fixed ] tag be backticks like every other loving markup :mad:

Adbot
ADBOT LOVES YOU

bitprophet
Jul 22, 2004
Taco Defender

JoeNotCharles posted:

But ! will cause you lots of headache, even though it's legal. (Worse than the others actually because it'll happily create it and then the shell will interpret ! weirdly - even when you try to escape it - so it'll be hard to refer to.)

Regular old quoting doesn't work with bang characters? :raise:

And, yea, obviously any character that has a special meaning in your shell (which is, unfortunately, most non-alphanumeric ones) is going to cause problems when unquoted.

  • Locked thread