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
Jarl
Nov 8, 2007

So what if I'm not for the ever offended?

king_kilr posted:

When an object is deallocating it decrefs anything it has a reference to, it's trivial to construct a chain of objects that would result in O(n) work being done on dealloc, no compaction necessary.

You're right. I am a moron. :)

To all: Thanks for all the input. It has been really helpful.

Jarl fucked around with this message at 21:56 on Feb 11, 2011

Adbot
ADBOT LOVES YOU

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

Stabby McDamage posted:

If you're worried about non-determinism, why not just run it for multiple replications (as you should be anyway to be statistically sound), then if you have a high standard deviation, you know something's up. I bet you won't. Even if it's non-deterministic, if the effect is less than 1%, then variances due to a ton of other factors will likely dominate.
In the Haskell community, we use a popular library named "criterion" to do this sort of benchmarking. It runs the benchmark a few dozen/hundred/thousand times, then summarises the results into something like this:



Out of curiosity, would any of you folks be interested in an article about benchmarking Python libraries with it?

Apocadall
Mar 25, 2010

Aren't you the guitarist for the feed dogs?

I'm new to programming and have experimented on and off past couple years with multiple languages but never really had the mind of a programmer so it was more just taking stuff and how I knew what it already did and applying it. I checked out the MIT OpenCourseWare site in the OP and was giddy with glee at just how much information is available there and how its structured.

I actually feel like I'm starting to think like a programmer now and it's awesome.

zarg
Mar 19, 2005

We are the Unity 3D community. You will be assimilated. Resistance is futile.
How do I coerce an item in a list into a float? For instance, I have a list containing several variables, each of which contains a single integer. I want to use just one entry at a time in another function, and perform some basic math with it. However, when I do something like

code:
list1 = [1, 2]
var = list1[0:1] * 2
Python treats the "list1" item as a list and just prints it's value twice instead of multiplying it as an int or float. I've tried

code:
var = float(list1[0:1]) * 2
And that does not seem to work either. I'm sure I'm missing something basic here, but I wasnt able to find anything too instructive on google when I looked.

Duurp?

Threep
Apr 1, 2006

It's kind of a long story.
I'm not sure exactly what you're after but maybe this'll put you in the right direction:

code:
>>> list1 = [1, 2]
>>> [float(x * 2) for x in list1]
[2.0, 4.0]
>>> [x * 1.5 for x in list1]
[1.5, 3.0]
>>> map(lambda(x): x * 1.5, list1)
[1.5, 3.0]
If what you're trying to do is call a function with every element in the list and return a list of the results, map is definitely what you're after:
code:
>>> list1 = [1, 2]
>>> def dostuff(x):
...   return x * 1.5
...
>>> map(dostuff, list1)
[1.5, 3.0]

Scaevolus
Apr 16, 2007

zarg posted:

code:
list1 = [1, 2]
var = list1[0:1] * 2
Duurp?
If you want to get a single element from a list, don't use slice notation:
code:
list1 = [1, 2]
var = list1[0] * 2
foo[a:b] gets a slice (sub-list) of the original list, foo[a] gets an element.

zarg
Mar 19, 2005

We are the Unity 3D community. You will be assimilated. Resistance is futile.

Threep posted:

I'm not sure exactly what you're after but maybe this'll put you in the right direction:

So I cant slice out part of the list and do the work on just that slice? I have to update the entire list at once?

Ideally what I want to do is just use one part of the list in a calculation, then use the result of that to update another value in the list.

edit:

Scaevolus posted:

If you want to get a single element from a list, don't use slice notation:
code:
list1 = [1, 2]
var = list1[0] * 2
foo[a:b] gets a slice (sub-list) of the original list, foo[a] gets an element.

I am such a moron. I knew this too, but we just learned about slices in my intro class and I thought I'd be clever and use them :( Thanks!

zarg fucked around with this message at 01:08 on Feb 15, 2011

Tetramin
Apr 1, 2006

I'ma buck you up.
I feel like this should be a really easy solution and I'm just being a retard.

I'm trying to search a dictionary for a match, full or partial, and print the full key and the value, and if it cannot find any matches, print that it can't.

code:
def search(self,name):
    for key in self.c:
        if re.search('{0}'.format(name),'{0}'.format(key)):
            print('found key {0} - value {1}'.format(key, self.c[key]))
works just fine, now if I just add an else for false, it prints that it couldn't find the key for each key it iterates through, obviously because it's inside of the for loop.

basically i want the output to be
code:
found key -- value

or

could not find key.
rather than
code:
found key --value
could not find key
could not find key
could not find key
This is probably simple, but I can't figure this stupid poo poo out.

tef
May 30, 2004

-> some l-system crap ->
code:
>>> matches = [(k,v) for (k,v) in e.items() if k.find('E') >=0]
>>> if matches:
...     print matches
... else:
...     print 'no matches'

Scaevolus
Apr 16, 2007

Funnehman posted:

I'm trying to search a dictionary for a match, full or partial, and print the full key and the value, and if it cannot find any matches, print that it can't.

code:
def search(self, name):
    for key, value in self.c.iteritems():
        if name in key:
            print('found key {0} - value {1}'.format(key, value))
            break
    else:
        print 'not found'

Dren
Jan 5, 2001

Pillbug

Funnehman posted:

code:
def search(self,name):
    for key in self.c:
        if re.search('{0}'.format(name),'{0}'.format(key)):
            print('found key {0} - value {1}'.format(key, self.c[key]))

You have some clumsy syntax here.

code:
'{0}'.format(name)
would be better written as
code:
name
or, if you are not certain that name is a string
code:
str(name)
Also, print does not need parenthesis around its arguments and I prefer the % syntax to the c# .format style of string formatting.
e.g. this
code:
print('found key {0} - value {1}'.format(key, self.c[key]))
looks better like
code:
print 'found key %s - value %s' % (key, self.c[key])
This is still a bit clumsy. If you're going to be using the values of the dictionary whose keys you're iterating you really ought to iterate through iteritems().
e.g.
code:
for key in self.c:
becomes
code:
for key, value in self.c.iteritems()
This lets you write the print line as
code:
print 'found key %s - value %s' % (key, value)
which is eminently better than the original syntax.

To obtain your desired behavior you should take one of two approaches depending on what you might want to do with your search results.

One, keep track of whether or not any matches were found (this is the minimum requirement for achieving your desired output).
code:
def search(self, name):
    found = False
    for key, value in self.c.iteritems():
        if name in key:
            print 'found key %s - value %s' % (key, value)
            found = True
    if not found:
        print 'not found'
Two, store all of the matches. You might want to pass them to another part of your program.
code:
def search(self, name):
    results = []
    for key, value in self.c.iteritems():
        if name in key:
            results.append( (key, value) )
    self.printResults(results)
    return results

def printResults(self, results):
    for key, value in results:
        print 'found key %s - value %s' % (key, value)
    if len(results) == 0:
        print 'not found'
you can also compute the results as a one-liner
code:
results = [(k, v) for (k, v) in self.c.iteritems() if name in k]
tef's solution works, though Scaevolus's won't since it quits after the first match. I borrowed Scaevolus's use of 'name in key' since it is nicer syntax than using a regular expression or a find. Also, I've never seen for-else before, that's neat.

Please fix the '{0}'.format(name) stuff. It reminds me of when my coworker created a program with many dictionaries that got all of their values via dict.update({'key name' : value}). He didn't realize that he could say dict['key name'] = value.

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

In Python 3 you'll need parens around the string to print, so you might as well start getting used to it now.

Lurchington
Jan 2, 2003

Forums Dragoon
for that matter, I do stuff like: '{0}'.format(name) so I can easily add to it, or add a !r conversion or something. it's not the worst. In the same way it's not a bad idea to add parentheses to a print statement yourself so you can search+replace it to logging calls later

Lurchington fucked around with this message at 19:03 on Feb 16, 2011

Dren
Jan 5, 2001

Pillbug

Lurchington posted:

for that matter, I do stuff like: '{0}'.format(name) so I can easily add to it, or add a !r conversion or something. it's not the worst. In the same way it's not a bad idea to add parentheses to a print statement yourself so you can search+replace it to logging calls later

Writing code so you can add to it "later" is silly unless you're sure later is coming sooner rather than later. It's the design equivalent of premature optimization. If you need logging then by all means, add logging and in the meantime use syntax to support it. If you know you'll need to add to '{0}'.format(name), then use that syntax. Otherwise, use the simpler syntax.

I am not sure what a !r conversion is. Are you talking about the r in front of the string to make it a literal string?

I didn't know about python 3 print being a function. The parens are the future. Everything I work on is stuck in 2.6 so I haven't learned about python 3.

Lurchington
Jan 2, 2003

Forums Dragoon

Dren posted:

Writing code so you can add to it "later" is silly unless you're sure later is coming sooner rather than later. It's the design equivalent of premature optimization. If you need logging then by all means, add logging and in the meantime use syntax to support it. If you know you'll need to add to '{0}'.format(name), then use that syntax. Otherwise, use the simpler syntax.

I am not sure what a !r conversion is. Are you talking about the r in front of the string to make it a literal string?

I didn't know about python 3 print being a function. The parens are the future. Everything I work on is stuck in 2.6 so I haven't learned about python 3.

'{0}'.format(name) implicitly invokes the name.__format__ method
'{0!r}'.format(name) explicitly invokes the name.__repr__ method
'{0!s}'.format(name) explicitly invokes the name.__str__ method
http://docs.python.org/library/string.html#format-string-syntax
the BNF lists 's' and 'r' as conversions

In fairness you're advocating a stylistic preference in an area not even tangentially covered by the main style guide for the whole language (PEP-8). Along the way suggesting that people use %-style formatting that's essentially replaced in favor of the format string method. All in response to a post that wasn't asking for general stylistic feedback.

I provided a reason why someone might gild the lilly in this area: you figure that you're probably beef up that log line at some point so why not put extra boilerplate on now. Not a good enough reason to make people switch to that format, but certainly not something that's unreadable, unclear, or uncommon as far as these things go.

Lurchington fucked around with this message at 21:29 on Feb 16, 2011

Fehler
Dec 14, 2004

.
How is print('{0!r}'.format(name)) better than print(repr(name)) though? In my eyes the latter looks a lot cleaner and easier to understand.

Dren
Jan 5, 2001

Pillbug

Lurchington posted:

'{0}'.format(name) implicitly invokes the name.__format__ method
'{0!r}'.format(name) explicitly invokes the name.__repr__ method
'{0!s}'.format(name) explicitly invokes the name.__str__ method
http://docs.python.org/library/string.html#format-string-syntax
the BNF lists 's' and 'r' as conversions

In fairness you're advocating a stylistic preference in an area not even tangentially covered by the main style guide for the whole language (PEP-8). Along the way suggesting that people use %-style formatting that's essentially replaced in favor of the format string method. All in response to a post that wasn't asking for general stylistic feedback.

I provided a reason why someone might gild the lilly in this area: you figure that you're probably beef up that log line at some point so why not put extra boilerplate on now. Not a good enough reason to make people switch to that format, but certainly not something that's unreadable, unclear, or uncommon as far as these things go.
Gotta cede the point on % vs format to you. I didn't know that the .format syntax is replacing the % syntax.

However, I don't think potential for gilding the lilly is a good reason to use more complicated syntax in the case of the code in question. 'name in key' is much more terse and readable than formatted strings inside a regex search. Also, I don't believe in gilding lillies. Gilding lillies adds unnecessary complexity to code.

I also wish that Python would eliminate support for the % syntax altogether if they're replacing it with the .format syntax. Having multiple ways to skin a cat is very Perl and contributes to people like me being idiots and advocating the old stuff.

Lurchington
Jan 2, 2003

Forums Dragoon

Fehler posted:

How is print('{0!r}'.format(name)) better than print(repr(name)) though? In my eyes the latter looks a lot cleaner and easier to understand.

It's not better, but my point was that if someone already had it as {0!r}, I don't think I'd tell them to switch.

Dren posted:

However, I don't think potential for gilding the lilly is a good reason to use more complicated syntax in the case of the code in question

Somehow I thought it'd be a good time to drop a British (where I'm not from) idiom that people don't normally say. To "gild the lily" means to over-ornament something, and that's exactly what print('{0!r}'.format(name)) is to me. It's a lot of boilerplate (which isn't great) but I think it's at least inoffensive if you know you'll probably come back to it later anyways.

I think? %-syntax is being taken out in 3.x, but I'm not sure. It's pythonic to have one clear way of doing things, but just as much not breaking backwards compatibility. getopt, optparse and argarse are all in the standard library too. Even it argparse is now the only one not deprecated.

Lurchington fucked around with this message at 19:07 on Feb 17, 2011

defmacro
Sep 27, 2005
cacio e ping pong

Janin posted:

Out of curiosity, would any of you folks be interested in an article about benchmarking Python libraries with it?

I'd be interested.

tef
May 30, 2004

-> some l-system crap ->
edit: welp;

posted in the wrong thread.

Stephen Smith
Nov 8, 2004

«The Grimace Reaper»
Another small Python question. I'm getting an unusual error when I run the following code:

pre:
import math

v1 = 1.00
v2 = 0.00
v3 = 1.00

w11 = 0.00
w12 = 0.25
w13 = 0.25
w21 = 0.25
w22 = 0.00
w23 = -0.25
w31 = 0.25
w32 = -0.25
w33 = 0.00

theta = 0.3

for i in range(0,5):
    v1 = 1/(1 + math.exp(-3(w12*v2 + w13*v3 - theta)))
    v2 = 1/(1 + math.exp(-3(w21*v1 + w23*v3 - theta)))
    v3 = 1/(1 + math.exp(-3(w31*v1 + w32*v2 - theta)))
    print "v1 = ", v1
    print "v2 = ", v2
    print "v3 = ", v3
The error I get is:
Traceback (most recent call last):
File "nn.py", line 20, in <module>
v1 = 1/(1 + math.exp(-3(w12*v2 + w13*v3 - theta)))
TypeError: 'int' object is not callable

Any idea what might be going on here?

DeciusMagnus
Mar 16, 2004

Seven times five
They were livin' creatures
Watch 'em come to life
Right before your eyes

Stephen Smith posted:

The error I get is:
Traceback (most recent call last):
File "nn.py", line 20, in <module>
v1 = 1/(1 + math.exp(-3(w12*v2 + w13*v3 - theta)))
TypeError: 'int' object is not callable

Any idea what might be going on here?

There's no implicit multiplication. Try
pre:
    v1 = 1/(1 + math.exp(-3*(w12*v2 + w13*v3 - theta)))
    v2 = 1/(1 + math.exp(-3*(w21*v1 + w23*v3 - theta)))
    v3 = 1/(1 + math.exp(-3*(w31*v1 + w32*v2 - theta)))

DICTATOR OF FUNK
Nov 6, 2007

aaaaaw yeeeeeah
I'm having a frustrating problem with MySQLdb and I can't figure out this behavior.

I have this code performing a simple operation to pull a value out of a database:

code:
db = MySQLdb.connect(host="mysql", user="***", passwd="***", db="***")
cursor = db.cursor()
cursor.execute("SELECT PSDsn FROM student_ad WHERE sAmaccountname = '2016203'")
psdsn = cursor.fetchall()
print psdsn[0][0]
Now, that query when executed pretty much anywhere else returns 0102, as it should. However, when using MySQLdb...

code:
>>> print psdsn[0]
(102L,)
>>> print psdsn[0][0]
102
What gives, or is the real problem my usage of MySQLdb?

tripwire
Nov 19, 2004

        ghost flow

root beer posted:

I'm having a frustrating problem with MySQLdb and I can't figure out this behavior.

I have this code performing a simple operation to pull a value out of a database:

code:

db = MySQLdb.connect(host="mysql", user="***", passwd="***", db="***")
cursor = db.cursor()
cursor.execute("SELECT PSDsn FROM student_ad WHERE sAmaccountname = '2016203'")
psdsn = cursor.fetchall()
print psdsn[0][0]

Now, that query when executed pretty much anywhere else returns 0102, as it should. However, when using MySQLdb...

code:

>>> print psdsn[0]
(102L,)
>>> print psdsn[0][0]
102

What gives, or is the real problem my usage of MySQLdb?

You need to use a type conversion dictionary if you don't want mysqldb to try and guess how your data is to be converted. MYSQL returns all values as strings and they have to be converted from there; try long("0120") and see what you get.

Dren
Jan 5, 2001

Pillbug

root beer posted:

I'm having a frustrating problem with MySQLdb and I can't figure out this behavior.

I have this code performing a simple operation to pull a value out of a database:

code:
db = MySQLdb.connect(host="mysql", user="***", passwd="***", db="***")
cursor = db.cursor()
cursor.execute("SELECT PSDsn FROM student_ad WHERE sAmaccountname = '2016203'")
psdsn = cursor.fetchall()
print psdsn[0][0]
Now, that query when executed pretty much anywhere else returns 0102, as it should. However, when using MySQLdb...

code:
>>> print psdsn[0]
(102L,)
>>> print psdsn[0][0]
102
What gives, or is the real problem my usage of MySQLdb?
Is it that your data is in a tuple that upsets you?

That's because you're using fetchall. If you use fetchone you'll get the result you expect.

If you had a query that generated more than one result you might do this:
code:
cursor.execute("SELECT PSDsn FROM student_ad WHERE sAmaccountname LIKE '20%%'")
psdsns = cursor.fetchall()

for psdsn in psdsns:
  print psdsn
Having fetchall always return results in a tuple keeps that for loop from behaving unexpectedly when there is only one result.

Also, MySQLdb gives you back all integers as python longs, hence the L after the 102.

DICTATOR OF FUNK
Nov 6, 2007

aaaaaw yeeeeeah

Dren posted:

Is it that your data is in a tuple that upsets you?

That's because you're using fetchall. If you use fetchone you'll get the result you expect.

If you had a query that generated more than one result you might do this:
code:
cursor.execute("SELECT PSDsn FROM student_ad WHERE sAmaccountname LIKE '20%%'")
psdsns = cursor.fetchall()

for psdsn in psdsns:
  print psdsn
Having fetchall always return results in a tuple keeps that for loop from behaving unexpectedly when there is only one result.

Also, MySQLdb gives you back all integers as python longs, hence the L after the 102.
The problem is that it should be returning 0102, not 102. I don't get why it's trimming the preceding 0. :confused:

Lurchington
Jan 2, 2003

Forums Dragoon
there may be some sort of naive call of result_string.is_digit() and if so, it casts?

tripwire
Nov 19, 2004

        ghost flow

root beer posted:

The problem is that it should be returning 0102, not 102. I don't get why it's trimming the preceding 0. :confused:

Like I said, mysql doesn't spit out data in whatever format you want; it spits out strings. The library you are using is automatically converting fields which looks like numerical values to longs; and if you read the documentation for mysqldb, it covers how to pass in a type-conversion dictionary which will do what you want.

Stephen Smith
Nov 8, 2004

«The Grimace Reaper»

DeciusMagnus posted:

There's no implicit multiplication. Try
pre:
    v1 = 1/(1 + math.exp(-3*(w12*v2 + w13*v3 - theta)))
    v2 = 1/(1 + math.exp(-3*(w21*v1 + w23*v3 - theta)))
    v3 = 1/(1 + math.exp(-3*(w31*v1 + w32*v2 - theta)))

What a silly oversight. Thanks, it's clearly been a while.

DICTATOR OF FUNK
Nov 6, 2007

aaaaaw yeeeeeah

tripwire posted:

Like I said, mysql doesn't spit out data in whatever format you want; it spits out strings. The library you are using is automatically converting fields which looks like numerical values to longs; and if you read the documentation for mysqldb, it covers how to pass in a type-conversion dictionary which will do what you want.
Thanks, you were right. I now have it convert to a string and it returns the right value.

king_kilr
May 25, 2007

tripwire posted:

Like I said, mysql doesn't spit out data in whatever format you want; it spits out strings. The library you are using is automatically converting fields which looks like numerical values to longs; and if you read the documentation for mysqldb, it covers how to pass in a type-conversion dictionary which will do what you want.

This is complete nonsense, MySQLDb is returning a number, it happens to be a long. When you print the tuple of data tuple.__str__ calls each items *repr* which for longs includes the L char, however long.__str__ doesn't include the L.

Jarl
Nov 8, 2007

So what if I'm not for the ever offended?
I'm unsure how the following works under the hood.

code:
def foo():
    i=0
    def bar():
        return i+1
    i=i+1
    return bar

print(foo()())
Output: 2

- If the function object bar is created using i as a constant then the result would be 1.
- Maybe the created function object bar have a pointer to i that it uses when it is invoked, but in that case i has been popped from the stack at that point (nothing has overwritten it yet in this example, but I doubt that is what is going on)

What is actually going on?

Captain Capacitor
Jan 21, 2008

The code you say?

Jarl posted:

I'm unsure how the following works under the hood.

code:
def foo():
    i=0
    def bar():
        return i+1
    i=i+1
    return bar

print(foo()())
Output: 2

- If the function object bar is created using i as a constant then the result would be 1.
- Maybe the created function object bar have a pointer to i that it uses when it is invoked, but in that case i has been popped from the stack at that point (nothing has overwritten it yet in this example, but I doubt that is what is going on)

What is actually going on?

What happens is that bar is somewhat aware of the context in which it was created. When bar is executed, the interpreter has to find out which 'i' is referred to, so it moves up the chain. Since it's not in bar, it looks one level up, the context in which bar was created. If 'i' wasn't there, it would continue to go up the chain until it reached the global level.

Here's a quick order to how things are executing in this example:
1. foo() is called
2. i is set to 0
3. bar is created
4. i is set to 1
5. bar is returned and called
6. 1+1 is returned to print

zarg
Mar 19, 2005

We are the Unity 3D community. You will be assimilated. Resistance is futile.
I have started writing a really basic (and lovely) text game just to cut my teeth on as I'm still pretty new to this. One thing I've done is include a "help" menu of kinds so the player can type "about <option name>" and get a printout with some documentation on what that option does, without losing their place in the game by exiting to another branch of code or anything. Is this a sane way to handle things? Are there any problems this will create that I'm totally not seeing?

code:
def aboutmenu(x, y): #about catch-all. x reads from multichoice, which gets updated for each new 'screen.' y is our help text
    if multichoice == x:
        print '\n' + str(x[6:]) + "  -  " + str(y) + '\n'

aboutmenu ("about strength", "strength dictates how much physical damage you deal")
aboutmenu ("about stamina", "stamina dictates how much health your character has")
aboutmenu ("about perception", "perception dictates how much ranged/magic damage you deal")
Multichoice is just raw_input("Please pick an option: ") and I call it any time I want the user to make a choice. The aboutmenu options here are from the "screen" during character creation where the user is assigning stat points. Users can either type "strength" and then a number to add to strength, or "about strength" to get our help text.

Jarl
Nov 8, 2007

So what if I'm not for the ever offended?

Captain Capacitor posted:

What happens is that bar is somewhat aware of the context in which it was created. When bar is executed, the interpreter has to find out which 'i' is referred to, so it moves up the chain. Since it's not in bar, it looks one level up, the context in which bar was created. If 'i' wasn't there, it would continue to go up the chain until it reached the global level.

But that would mean an i is stored on a global level outside of the stack. This would have to be done for every invocation of foo.

Jarl fucked around with this message at 11:35 on Feb 20, 2011

Grabulon
Jul 25, 2003

I'm doing my first larger Python project, which is an IRC-bot based on Phenny, basically just writing my own functions (such as ".temperature" or ".google") for it. My question is how do I clean up the trigger-function?

code:
def found_terminator(self):
    ...
    ...
    if text[0] == "!":
        self.trigger(text, args, source)
    ...

#This:
def trigger(self, text, args, source):
    ...
    if ".google" in text:
        response = google.result(text)
    elif ".time" in text:
        response = get_time()
    ...
    ...
    ...
#etc
Basically a long list of if-statements, which looks pretty bad (and my Python skills aren't good enough to figure out how it's done in Phenny). What's a better way to do this?

tripwire
Nov 19, 2004

        ghost flow

king_kilr posted:

This is complete nonsense, MySQLDb is returning a number, it happens to be a long. When you print the tuple of data tuple.__str__ calls each items *repr* which for longs includes the L char, however long.__str__ doesn't include the L.
Holy loving god why does no one believe me, I'm quoting right from the documentation



quote:

The other oddity is: Assuming these are numeric columns, why are they returned as strings? Because MySQL returns all data as strings and expects you to convert it yourself. This would be a real pain in the rear end, but in fact, _mysql can do this for you. (And MySQLdb does do this for you.) To have automatic type conversion done, you need to create a type converter dictionary, and pass this to connect() as the conv keyword parameter.

Jarl
Nov 8, 2007

So what if I'm not for the ever offended?
About my earlier question regarding the implementation of non-locality: I now have no doubt that it is accomplished by allocating "i" on the heap when foo is invoked, which is pointed to by any function object created inside it that uses it. All this extra work is of course only done if the pre-interpretation-compilation discover that "i" will indeed be used in foo's inner functions.

Also, I just went through the Python tutorial over the last few days and I'm feeling confident that it is going to be my new favorite language for all relatively small programming tasks.

Jarl fucked around with this message at 18:28 on Feb 20, 2011

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

Jarl posted:

All this extra work is of course only done if the pre-interpretation-compilation discover that "i" will indeed be used in foo's inner functions.

Do you have a citation for this? I thought python object allocations always happened on the heap, as in most garbage-collected languages.

Adbot
ADBOT LOVES YOU

Jarl
Nov 8, 2007

So what if I'm not for the ever offended?

ShoulderDaemon posted:

Do you have a citation for this?

No, but it is my best bet and it would work.

ShoulderDaemon posted:

I thought python object allocations always happened on the heap, as in most garbage-collected languages.

In every language I've come across with immutable static sized objects (like ints) have it always been the case that they in actuality are allocated on the stack. - You can't tell the difference and it's faster and more memory efficient.

EDIT:
Have to be more clear: Only SMALL immutable static sized objects. Static sized means that all instances of that type have the same size, i.e. even though a tuple in python is immutable it is NOT static in size since different tuples can consist of a different number of entries.

Especially ints are perfect for just storing on the stack. Might as well store the value instead of an address to a value. Since it is immutable it makes no difference.

Jarl fucked around with this message at 19:24 on Feb 20, 2011

  • Locked thread