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
Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Gothmog1065 posted:

Is there a good source so I can read up on the difference, etc? The book I used barely covered libraries and such.

Modules are libraries. What you'd have is a file called something like my_commands.py that contains something like:

code:
import subprocess
import webbrowser

def web_open(url):
    webbrowser.open(url)

def map_drive(drive_letter, location):
    p = subprocess.Popen(['subst', drive_letter, location])
    p.wait()
and then you make a script like this:

code:
from my_commands import web_open, map_drive

web_open("http://google.com/")
web_open("http://example.com")
map_drive("Q:", "C:/foo/bar/baz/bonghits")

Gothmog1065 posted:

Eventually I want this to be part of a larger program that will do some of the tasks at work to make things easier. For example, we use IPs a lot, I'd like to eventually have it where I can put an IP in to a box and have it do various functions depending on the need.

Designing your own language is a hard task. Right now you're simply splitting strings based on ",". What if you want to insert a comma character into one of your parameters? Then you have to stop using string manipulation and build a real language where you use something like:

code:
web_open,"http://foo.com/a,b,c"
and while you're at it, why not add make it look like a real language:

code:
web_open("http://foo.com/a,b,c")
To implement this sanely, you'd have to write a real parser. For reference, the way you would do that is to decompose the byte stream into tokens. A simple token stream would be:

code:
IDENTIFIER(name="web_open")
OPEN_PAREN
STRING(content="http://foo.com/a,b,c")
CLOSE_PAREN
After this, you would evaluate the token stream based on a set of rules to get a parse tree. The rules might be:

  • a FunctionCall is made up of an IDENTIFIER, an OPEN_PAREN, an ArgList, and a CLOSE_PAREN.
  • an ArgList is made up of a Parameter, followed by zero or more pairs of COMMA, Parameter
  • a Parameter is made up of a STRING, a NUMBER or a BOOLEAN

Using these rules, a parse tree for the above stream might look like:

code:
FunctionCall(
    IDENTIFIER(name="web_open"),
    ArgList(
         Parameter(STRING(content="http://foo.com/a,b,c"))
    )
)
From there, you would interpret the parse tree directly by interpreting the nodes. You would look at the FunctionCall node, and then make the decision of what function to call based on the identifier. You'd decide what arguments to pass based on the ArgList.

All of this work is rebuilding Python, which does all this already and a lot more, for no good reason. It's a good learning experience, but inventing your own language should never be done "in production".

EDIT: To come from the other side, every custom language is something new for other people to learn. By making your IT staff learn a custom, less-powerful utility and custom, less-powerful language isn't really an efficient use of time either. This tool probably won't be used outside of your staff, so learning it isn't broadening their skills.

Gothmog1065 posted:

I'm on 3.2.1 right now, going to update, I though I was on 3.1.3, but whatever. I keep hearing different reasons to either be updated or go back. I know 2.x has much better library and addon support, but for the basic stuff right now, will it make a difference?

Get used to examples and tutorials written for Python 2.x, not 3.x. Get used to being able to use third-party supplied libraries. Programmers quite often need to use third-party code because it's commonly a waste of time and effort to rebuild it themselves. Working with third-party libraries and frameworks is very good practice, and the availability of third-party libraries is much higher in 2.x than in 3.x.

2.7 has most of the good 3.x features anyway. Between 2.7 and 3.x, there aren't that many good reasons to switch over, while a lot of downsides.

Gothmog1065 posted:

anyhoo:

pre:
Traceback (most recent call last):
  File "C:\Users\Gothmog\Desktop\Python\Script.py", line 61, in <module>
    main(0)
  File "C:\Users\Gothmog\Desktop\Python\Script.py", line 53, in main
    split_commands = command.split(',')
UnboundLocalError: local variable 'command' referenced before assignment
That's the first thing I'm having an issue with.

Gah, as The Gripper said, I hosed up. Should be line.split.

Suspicious Dish fucked around with this message at 08:52 on Nov 28, 2011

Adbot
ADBOT LOVES YOU

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

Suspicious Dish posted:

2.7 has most of the good 3.x features anyway. Between 2.7 and 3.x, there aren't that many good reasons to switch over, while a lot of downsides.

I'm just tired of typing from __future__ import division in every single goddamn file/interactive session

NumPy + SciPy + NetworkX + BioPython = 3.2 supremacy :smug:

Modern Pragmatist
Aug 20, 2008
So I need to write some unit tests for an app that I've written for sorting files based on meta-data. I was assuming I should just use PyUnit since it's part of the standard library, but I'm open to other suggestions.

My main question though, was how exactly to go about setting up test cases. The most basic test would ensure that files (of various types) are sorted properly. I'm having a hard time thinking of a way to provide the correct sorting to validate against. My initial idea is to run the sorting, then get a directory listing of the destination directory and compare this to a known directory listing when the sorting occurs correctly. Where would I store this known listing? As a pickled list? A text file?

I've done some unit tests in other languages before, but they all dealt with mathematical tests rather than something like a file sorting app.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Why not just store the expected data as a list within the Python program?

code:
from mylib import sort_files
import unittest

class FileSorterTests(unittest.TestCase):
    def test_files_sorted(self):
        sorted_files = sort_files("foo/")
        expected = ['a', 'b', 'c']
        self.assertEqual(sorted_files, expected)

Modern Pragmatist
Aug 20, 2008

Suspicious Dish posted:

Why not just store the expected data as a list within the Python program?

Wow. Yeah that should work.

Another question. All of my processing is done in a separate thread from my gui using threading.Thread A problem that I am having is that the thread never seems to release the memory that it allocates while running. Do I have to manually clean up the thread after it finishes executing the run method?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
That's a very generic question. You're not supposed to do any cleanup. The GC will do it for you. What sort of processing are you doing?

EDIT: Do note that Python has the Global Interpreter Lock, meaning that two Python threads can't run at once. While your GUI will continue to update because it runs on its own thread, something like a Python callback will have to wait until a thread releases the GIL. If you're using numpy, that releases the GIL by itself. If you do any blocking IO, it will release the GIL while waiting for the IO to complete. If you're stuck in a while loop, the GIL won't be released and your callback won't be run.

Suspicious Dish fucked around with this message at 03:37 on Nov 30, 2011

mdxi
Mar 13, 2006

to JERK OFF is to be close to GOD... only with SPURTING

Modern Pragmatist posted:

A problem that I am having is that the thread never seems to release the memory that it allocates while running.

Generally speaking, "dynamic" languages don't release memory to the OS during execution.

The runtime allocates a heap at startup, and this is what your program sees as "memory". As your program's memory usage goes up, the runtime will allocate more memory from the OS and portion that out to your program, again on an as-needed basis.

When your program's variables and/or structures go out of scope and/or their reference counts fall to zero and/or you explicitly destroy them, the language runtime marks that portion of its heap free. Memory is not returned to the OS until execution ends, because the runtime expects that it will use that heap again.

You don't have direct control over memory from an OS perspective, and even indirectly you can only cause more of it to be used. You should expect that your process's overhead will grow to the size of the runtime overhead plus the size of your maximum heap allocation, and then remain near-constant for the life of the process.

Modern Pragmatist
Aug 20, 2008

mdxi posted:

Generally speaking, "dynamic" languages don't release memory to the OS during execution.

The runtime allocates a heap at startup, and this is what your program sees as "memory". As your program's memory usage goes up, the runtime will allocate more memory from the OS and portion that out to your program, again on an as-needed basis.

When your program's variables and/or structures go out of scope and/or their reference counts fall to zero and/or you explicitly destroy them, the language runtime marks that portion of its heap free. Memory is not returned to the OS until execution ends, because the runtime expects that it will use that heap again.

You don't have direct control over memory from an OS perspective, and even indirectly you can only cause more of it to be used. You should expect that your process's overhead will grow to the size of the runtime overhead plus the size of your maximum heap allocation, and then remain near-constant for the life of the process.

Ok this is pretty helpful. I'll run a few more tests tomorrow to make sure it's working as expected. Thanks for the explanation.

etcetera08
Sep 11, 2008

mdxi posted:

Generally speaking, "dynamic" languages don't release memory to the OS during execution.

The runtime allocates a heap at startup, and this is what your program sees as "memory". As your program's memory usage goes up, the runtime will allocate more memory from the OS and portion that out to your program, again on an as-needed basis.

When your program's variables and/or structures go out of scope and/or their reference counts fall to zero and/or you explicitly destroy them, the language runtime marks that portion of its heap free. Memory is not returned to the OS until execution ends, because the runtime expects that it will use that heap again.

You don't have direct control over memory from an OS perspective, and even indirectly you can only cause more of it to be used. You should expect that your process's overhead will grow to the size of the runtime overhead plus the size of your maximum heap allocation, and then remain near-constant for the life of the process.

Ah, this has been something I've been curious about as well. Do you have any sources that go into more detail about this? (Not to say your explanation isn't helpful! I'm just interested in some of the details.)

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

mdxi posted:

When your program's variables and/or structures go out of scope and/or their reference counts fall to zero and/or you explicitly destroy them, the language runtime marks that portion of its heap free. Memory is not returned to the OS until execution ends, because the runtime expects that it will use that heap again.

http://hg.python.org/cpython/file/74d182cf0187/Objects/obmalloc.c#l1080

No, Python uses free when it frees an object. That should be returned to the OS.

mdxi
Mar 13, 2006

to JERK OFF is to be close to GOD... only with SPURTING

Suspicious Dish posted:

http://hg.python.org/cpython/file/74d182cf0187/Objects/obmalloc.c#l1080

No, Python uses free when it frees an object. That should be returned to the OS.

My apologies. I was working from my knowledge of Perl 5 internals, and betting that any language with a similar design would take a similar approach.

tef
May 30, 2004

-> some l-system crap ->

mdxi posted:

My apologies. I was working from my knowledge of Perl 5 internals, and betting that any language with a similar design would take a similar approach.

Why would anyone ever think this. Perl internals are insane.

quote:

To reanimate the program, its parse tree must be reconstructed. This phase exists only if code generation occurred and you chose to generate bytecode. Perl must first reconstitute its parse trees from that bytecode sequence before the program can run. Perl does not run directly from the bytecodes; that would be slow.

Modern Pragmatist
Aug 20, 2008

Suspicious Dish posted:

http://hg.python.org/cpython/file/74d182cf0187/Objects/obmalloc.c#l1080

No, Python uses free when it frees an object. That should be returned to the OS.

So if this is true, are all objects that exist within a thread not removed and their memory freed upon completion of threading.Thread.run()?

As far as the contents of the thread, it loads a tar file, extracts certain parts and stores them into objects, which are then saved as modified files. It seems pretty trivial, however, the memory occupied by the objects is never released until I exit python.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Modern Pragmatist posted:

So if this is true, are all objects that exist within a thread not removed and their memory freed upon completion of threading.Thread.run()?

As far as the contents of the thread, it loads a tar file, extracts certain parts and stores them into objects, which are then saved as modified files. It seems pretty trivial, however, the memory occupied by the objects is never released until I exit python.

Python objects are freed when their reference counts are dropped to zero, or when the cycle detector sweeps them away. I'll need a code sample to see whether you're retaining the objects somehow.

Modern Pragmatist
Aug 20, 2008

Suspicious Dish posted:

Python objects are freed when their reference counts are dropped to zero, or when the cycle detector sweeps them away. I'll need a code sample to see whether you're retaining the objects somehow.

http://pastebin.com/5We2KrSq

The thread is spawned in FileDropTarget.DoProcessing()

tef
May 30, 2004

-> some l-system crap ->
code:
self.thread = Processor(files,path,self)
you're keeping a reference to the thread in self.thread

Modern Pragmatist
Aug 20, 2008

tef posted:

code:
self.thread = Processor(files,path,self)
you're keeping a reference to the thread in self.thread

I was under the impression that my very large variable (container) went out of scope after Processor.run() completed due to the fact that it is not a property of Processor. I ran a test by substituting:
code:
Processor(files,path,self)
And it still appears that the heap still holds onto the memory upon completion.

Modern Pragmatist fucked around with this message at 06:43 on Dec 1, 2011

Lister_of_smeg
May 25, 2005
I'm seeing something weird with urllib and simplejson. I'm sure I've just misunderstood something, but I can't see what. Therefore I've decided to throw it out here and see if any of you fine people can help.

I've condensed the problem I'm experiencing down to the following code.

code:
import simplejson
import urllib

request_dict = {
    'site' : 'uk',
    'id' : 1,
    }

print request_dict

print simplejson.dumps(request_dict)

print urllib.urlencode(request_dict)

print urllib.urlencode(simplejson.dumps(request_dict))
When I run it I get the following output.

code:
{'site': 'uk', 'id': 1}
{"site": "uk", "id": 1}
site=uk&id=1
Traceback (most recent call last):
  File "glm_rest.py", line 29, in <module>
    print urllib.urlencode(simplejson.dumps(request_dict))
  File "/tools/python/2.5.1/linux64/lib/python2.5/urllib.py", line 1236, in urlencode
    raise TypeError
TypeError: not a valid non-string sequence or mapping object
What I don't understand is why urlencode is happy with the raw dict, but not with the dict that comes out of simplejson.dumps.

Any ideas?

Johnny Cache Hit
Oct 17, 2011

Lister_of_smeg posted:

What I don't understand is why urlencode is happy with the raw dict, but not with the dict that comes out of simplejson.dumps.

code:
>>> type(simplejson.dumps(request_dict))
<type 'str'>
>>> type(request_dict)
<type 'dict'>
urlencode doesn't work on strings.

Why do you want to urlencode the simplejson output rather than just urlencode the request_dict? You're adding another step that doesn't really seem sensible.

Lister_of_smeg
May 25, 2005

Kim Jong III posted:

code:
>>> type(simplejson.dumps(request_dict))
<type 'str'>
>>> type(request_dict)
<type 'dict'>
urlencode doesn't work on strings.

Why do you want to urlencode the simplejson output rather than just urlencode the request_dict? You're adding another step that doesn't really seem sensible.

That makes sense. Must remember to check with type() in the future.

I was building out a RESTful interface that had been prototyped by one of the senior developers here. His prototype methods did it that way, so I figured I should follow suit. Looks like I need to ask some questions about how well tested this prototype is.

tef
May 30, 2004

-> some l-system crap ->
I am taking a guess and I am imagining that by restful you mean 'homeopathic rest'

crazyfish
Sep 19, 2002

Okay, I've run into a fairly annoying problem trying to develop a python module that interacts with two other modules that have a shared module hierarchy. Maybe this is me just coming from a mostly Java background and expecting this kind of thing to work, but hear me out, as I've been able to throw together a trivial example that illustrates what I'm trying to do.

Let's say I have two projects, test-1 and test-2 with the following directory hierarchies:

code:
test-1/foo/stuff/bar.py
test-2/foo/stuff2/baz.py
Also assume that both foo directories, stuff, and stuff2 also have __init__.py.

My PYTHONPATH is set up as follows:

code:
crazyfish@crazyfish-debian-vm:~# echo $PYTHONPATH
test-1:test-2
All seems okay. So now let's actually run the python interpreter:

code:
crazyfish@crazyfish-debian-vm:~# python
Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from foo.stuff import bar
>>> bar
<module 'foo.stuff.bar' from '/home/crazyfish/test-1/foo/stuff/bar.pyc'>
>>> from foo.stuff2 import baz
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named stuff2
>>> import sys
>>> print sys.path
['', '/home/crazyfish/test-1', '/home/crazyfish/test-2', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', 
'/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages', 
'/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/pymodules/python2.6/gtk-2.0']
>>>
So it looks like python is correctly recognizing the two paths, and it seems I can import baz correctly when I put test-2 first in the PYTHONPATH (though then I can't import bar). My question is, is there any way to work around this problem short of setting up some weird symlink hierarchy, or is what I'm trying to do not The Python Way?

edit: unbroke tables

crazyfish fucked around with this message at 01:19 on Dec 3, 2011

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Every module is a singleton. This means that between test-1/foo/__init__.py and test-2/foo/__init__.py, one of them has to "win". You can see which one wins by doing:

code:
>>> import foo
>>> foo.__file__
The best solution is just not doing that. The terrible solution is to use namespace packages, which are complicated pieces of magic which you shouldn't concern yourself with.

crazyfish
Sep 19, 2002

Suspicious Dish posted:

Every module is a singleton. This means that between test-1/foo/__init__.py and test-2/foo/__init__.py, one of them has to "win". You can see which one wins by doing:

code:
>>> import foo
>>> foo.__file__
The best solution is just not doing that. The terrible solution is to use namespace packages, which are complicated pieces of magic which you shouldn't concern yourself with.

Sigh. This just feels like another random instance of python's 'your way or the highway' kind of mentality, kind of ignoring the real need of enterprise types to organize their python modules, but never mind that.

This is good information to know, don't get me wrong. But it's another instance of python breaking what I feel is a reasonable use case. Then again, no language would ever get developed without someone compromising someones' reasonable use cases.

Catalyst-proof
May 11, 2011

better waste some time with you

crazyfish posted:

Sigh. This just feels like another random instance of python's 'your way or the highway' kind of mentality, kind of ignoring the real need of enterprise types to organize their python modules, but never mind that.

This is good information to know, don't get me wrong. But it's another instance of python breaking what I feel is a reasonable use case. Then again, no language would ever get developed without someone compromising someones' reasonable use cases.

What are you talking about? Enterprise types?

code:
>>> import test_1.foo
>>> import test_2.foo

# or

>>> from test_1 import foo as t1foo
>>> from test_2 import foo as t2foo
or

code:
# test_1/__init__.py
import foo

# test_2/__init__.py
import foo

>>> import test_1, test_2
>>> test_1.foo, test_2.foo
There's three separate ways to deal with it off the top of my head. Is your 'reasonable use case' the desire to have two modules in the namespace with the same name? Because... that's not really that reasonable.

quaunaut
Sep 15, 2007

WHOOSH
Hi again! I post here too rarely. I r nublet etc.

I'm trying to implement a quicksort algorithm into my code(mostly to figure it out, partly for the satisfaction), and I've got it pretty much there, except now I'm getting an error I don't know what to do with.

code:
def quickSort(sortThis):
    if len(sortThis) <= 1:
        return sortThis
    pivot = sortThis.pop(len(sortThis)/2)
    less = []
    greater = []
    for e in sortThis:
        if sortThis[e] <= pivot:
            less.append(sortThis[e])
        else: greater.append(sortThis[e])
    return [quickSort(less)] + [pivot] + [quickSort(greater)]
(Yes, I know that quicksorting thing from the middle is dumb, that's just in there to remind me to refine it)

The error I'm getting is tied specifically to anyplace sortThis[e] is mentioned in the above. The error itself:

code:
less.append(sortThis[e])
IndexError: list index out of range
Anyone have any ideas for why it would be out of the range?

crazyfish
Sep 19, 2002

Fren posted:

What are you talking about? Enterprise types?

code:
>>> import test_1.foo
>>> import test_2.foo

# or

>>> from test_1 import foo as t1foo
>>> from test_2 import foo as t2foo
or

code:
# test_1/__init__.py
import foo

# test_2/__init__.py
import foo

>>> import test_1, test_2
>>> test_1.foo, test_2.foo
There's three separate ways to deal with it off the top of my head. Is your 'reasonable use case' the desire to have two modules in the namespace with the same name? Because... that's not really that reasonable.

Yeah that was just me being dumb and angry. Thanks for the help.

TasteMyHouse
Dec 21, 2006

quaunaut posted:

Hi again! I post here too rarely. I r nublet etc.

I'm trying to implement a quicksort algorithm into my code(mostly to figure it out, partly for the satisfaction), and I've got it pretty much there, except now I'm getting an error I don't know what to do with.

code:
def quickSort(sortThis):
    if len(sortThis) <= 1:
        return sortThis
    pivot = sortThis.pop(len(sortThis)/2)
    less = []
    greater = []
    for e in sortThis:
        if sortThis[e] <= pivot:
            less.append(sortThis[e])
        else: greater.append(sortThis[e])
    return [quickSort(less)] + [pivot] + [quickSort(greater)]
(Yes, I know that quicksorting thing from the middle is dumb, that's just in there to remind me to refine it)

The error I'm getting is tied specifically to anyplace sortThis[e] is mentioned in the above. The error itself:

code:
less.append(sortThis[e])
IndexError: list index out of range
Anyone have any ideas for why it would be out of the range?

"for" loops in python are not like for loops in C or C++ -- they're 'foreach' loops. When you say for e in sortThis, what you're doing is creating a loop where e gets assigned to be the elements inside sortThis successively. For Example:

code:

lis=[10,9,8,7,6,5,4,3,2,1,0,1000,"lol python"]
for i in lis: print i

program output posted:

10
9
8
7
6
5
4
3
2
1
0
1000
lol python


So, you can see that the problem here is that you're saying sortThis[e] - you're taking e, which is an element in your list, and you're using it as an index into list -- check this out:

code:
lis=[10,9,8,7,6,5,4,3,2,1,0,1000,"lol python"]
for i in lis: print lis[i]

program output posted:

0
1
2
3
4
5
6
7
8
9
10
Traceback (most recent call last):
Line 2, in <module>
for i in lis: print lis[i]
IndexError: list index out of range

You can see that the IndexError exception is thrown on the last list iteration that it gets to, because the value 10000, when interpreted as an index into the list, is out of bounds. Also notice that even before that happens, because it's using the values in the list as indexes into the list, it's printing the list in reverse order -- probably not what was intended.

For fun, check out what happens if you remove the element 10000 from that list and then execute the loop.

if the value of e on that loop iteration is greater than the length of the list, you're gonna get that error you posted. Otherwise, the algorithm would just silently do the incorrect thing.

TasteMyHouse fucked around with this message at 07:00 on Dec 4, 2011

tef
May 30, 2004

-> some l-system crap ->

quaunaut posted:

Hi again! I post here too rarely. I r nublet etc.

I'm trying to implement a quicksort algorithm into my code(mostly to figure it out, partly for the satisfaction), and I've got it pretty much there, except now I'm getting an error I don't know what to do with.

code:
def quickSort(sortThis):
    if len(sortThis) <= 1:
        return sortThis
    pivot = sortThis.pop(len(sortThis)/2)
    less = []
    greater = []
    for e in sortThis:
        if sortThis[e] <= pivot:
            less.append(sortThis[e])
        else: greater.append(sortThis[e])
    return [quickSort(less)] + [pivot] + [quickSort(greater)]
(Yes, I know that quicksorting thing from the middle is dumb, that's just in there to remind me to refine it)

The error I'm getting is tied specifically to anyplace sortThis[e] is mentioned in the above. The error itself:

code:
less.append(sortThis[e])
IndexError: list index out of range
Anyone have any ideas for why it would be out of the range?

As mentioned earlier, for iterates over the values in a list, not the indices .

You might find it easier to implement quicksort that returns a new list before quicksorting in-place.

FoiledAgain
May 6, 2007

quaunaut posted:

Anyone have any ideas for why it would be out of the range?

I'm a little late to the party on this, but for loops iterate over values. If you want indices, try for j in range(len(sortThis))

Scaevolus
Apr 16, 2007

FoiledAgain posted:

I'm a little late to the party on this, but for loops iterate over values. If you want indices, try for j in range(len(sortThis))

I'm partial to for i, _ in enumerate(sortThis)

IShallRiseAgain
Sep 12, 2008

Well ain't that precious?

For some reason, input() randomly stopped working properly and it doesn't receive input as strings, but as variable or numbers unless I put quotations around the input. How in the world do I fix that? I'm using IDLE if that matters.

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

IShallRiseAgain posted:

For some reason, input() randomly stopped working properly and it doesn't receive input as strings, but as variable or numbers unless I put quotations around the input. How in the world do I fix that? I'm using IDLE if that matters.

In python 2, you should always use raw_input() - input() executes the input first and returns the result. In python 3 raw_input() changed to input().

IShallRiseAgain
Sep 12, 2008

Well ain't that precious?

Thanks, I didn't realize input() had changed between versions, and I had to use an older version of Python for an assignment.

TasteMyHouse
Dec 21, 2006
I'd like to note that this is ENTIRELY for my own edification:

I wanted to read 4 bytes from /dev/urandom, interpret those 4 bytes as an int, then use that int for some random purpose. The problem here is that if I do:
code:
with open("/dev/urandom") as file:
    number=file.readline(4)
number is now a 4 char long string. I could write low-level byte twiddly bullshit using ord() and bitwise shifts, ORs, etc to take these 4 bytes and create a single int out of them... but this is Python, not C! Surely there's an easier way?

Again note though: I'm just using random now so it doesn't matter at all, practically.

TasteMyHouse fucked around with this message at 19:44 on Dec 5, 2011

Threep
Apr 1, 2006

It's kind of a long story.

TasteMyHouse posted:

number is now a 4 char long string. I could write low-level byte twiddly bullshit using ord() and bitwise shifts, ORs, etc to take these 4 bytes and create a single int out of them... but this is Python, not C! Surely there's an easier way?
I don't know if there's a better way but:
code:
struct.unpack('I', file.readline(4))

TasteMyHouse
Dec 21, 2006

Threep posted:

I don't know if there's a better way but:
code:
struct.unpack('I', file.readline(4))

Awesome. This was exactly what I was looking for, thanks!

o.m. 94
Nov 23, 2009

I'm starting learning design patterns, and the first thing I stumble across is interfaces. Since I was learning from a Java tutorial, I kind of had to scratch my head and work out how to implement it in Python.

Would y'all be able to check my code and give any pointers / advice? (Unfortunately the output feature seems to be Python 2.x and I can't remember how to format strings in 2.x)

vikingstrike
Sep 23, 2007

whats happening, captain
I think you just need to do:

print dave

and

print "Hello, %s" % dave

At least, if I'm understanding what you're trying to do.

Adbot
ADBOT LOVES YOU

o.m. 94
Nov 23, 2009

vikingstrike posted:

I think you just need to do:

print dave

and

print "Hello, %s" % dave

At least, if I'm understanding what you're trying to do.

Ah thanks, although that's more of an aside. I'm really just interested to see if my implementation of an Interface is useful/correct; it's all in the code.

  • Locked thread