This just doesn't sound like a good idea. If it were me, I'd specify interfaces and let other programmers work out how to fulfill those interfaces.

For instance, the sum function expects an iterable of summable objects. It doesn't care if a programmer stores his or her data in a csv file, json file, shelve, or whatever. It's up to the programmer to get the data he or she wants to use in the correct structure; he or she has to fulfill the interface.

It's better. You don't have to worry about what other programmers are doing. You don't have to write code to fulfill the interface for every situation. You can just specify the interface and let other programmers fulfill it. It's more robust. They can handle situations that you can't foresee. It keeps your code lean.

P.S. When I asked what your case was, I was talking about the project that you are writing this system for. I assume you are writing this to address something in another project? If you aren't, you are "solving" a "problem" that doesn't need to be solved.

So you are pretty much trying to make functions and methods that behave differently depending on an argument's type or behavior? That's not a very good idea. It's very difficult to ensure that you can appropriately handle all types or behaviors in one function or method. Even if you can, you make it very difficult for yourself or other developers.

If your function or method returns a copy when the object is immutable, what does it return when the object is mutable? The same object? Now imagine you call this function and have to work with the return value. You pretty much have to do the same mutability checking you did in your function or method to ensure you handle the return value properly. This introduces more code, more overhead, and more points where your software can break.

I don't know any standard solutions. What is your specific case? Do you have any code?

I ran into this problem myself when I was working on some trivial neural network code. I wanted to use either a pair of sequences or a pair of mappings to represent a pair of neuron inputs and corresponding neuron weights. If the inputs was a sequence I would use the index of each input to look up the corresponding weight, or if the inputs was a mapping I would use the key of each input to look up the corresponding weight. At first I decided to use the collections abstract base classes to check if ...

Why do you need to check an object's mutability? Sounds like you need to solve a different problem or use a different solution. Technically you could try to make whatever changes you wanted to make and catch any AttributeError exceptions, but it still seems funny. So...?

hughesadam_87 commented: . +3

You can write a module that can also act as a script by using the idiom:

if __name__ == '__main__':
    pass

Importing a module and then executing the main body of that module is indicative of a design problem, but can be accomplished by wrapping the main body in a main function.

#module.py

def main():
    pass

if __name__ == '__main__':
    main()

#script.py

import module

module.main()

[url]http://en.wikipedia.org/wiki/Pseudorandom_number_generator[/url]

There is even a link to an algorithm with a psuedocode implementation.

Personally, I think you should find something else to work on. I think reimplementing established algorithms will provide little educational value.

I've never used it, but the subprocess module may be what you need. It seems to feature a function that will start a subprocess and wait for the subprocess exit code. If the exit code is non-zero then the function will raise an exception.

[COLOR="Green"]creature.metabolism[/COLOR]
[COLOR="Red"]creature.metabolsim[/COLOR]

vegaseat commented: upvoted for Griboullis (was downvote error) +15
Gribouillis commented: spot on -3

Hm. It seems like bisect assumes ascending order. I hadn't thought of descending order.

You can either write your own function or you can keep your data in ascending order until you need descending order.

It's possible to get a reverse iterator over a sequence using the function reversed.
A slice with a negative step will have reversed elements. Example: L[::-1]

I do think you should use bisect.

It works.

If you can be sure that your value will fall between two indices, you can specify a lower bound and an upper bound to restrict the search. (Thus reducing search times.)

The implementation isn't much different from your own.

[code=Python]def bisect_right(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted.

The return value i is such that all e in a[:i] have e <= x, and all e in
a[i:] have e > x.  So if x already appears in the list, a.insert(x) will
insert just after the rightmost x already there.

Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""

if lo < 0:
    raise ValueError('lo must be non-negative')
if hi is None:
    hi = len(a)
while lo < hi:
    mid = (lo+hi)//2
    if x < a[mid]: hi = mid
    else: lo = mid+1
return lo[/code]

If you can, check out the fractions module.

[url]http://docs.python.org/library/fractions.html#module-fractions[/url]

The source is included with Python. If you can locate it, you can see how the author(s) did it.

I can't tell if this is an exercise.

Even if it is, the bisect source can still serve as an inspiration and guideline.

It's strange how people don't realize that a lot of things are in the standard module library and the source is available for most of it.

Isn't this what the bisect module is for?

An object is just an abstraction of data and functions.

An object has attributes (data) and methods (functions that interact with its attributes).

A class is a blueprint describing the objects created from it.

When you write a class you are 'declaring' a class.

An object created from a class is an 'instance' of that class.

Objects are most useful when the systems you are modeling in your program can be abstracted as objects.

Anything you can refer to with a noun is a potential candidate.

I recommend that people learning object-oriented programming model concrete objects.

[url]http://www.chompchomp.com/terms/concretenoun.htm[/url]

I don't think there is a module or package providing key press event functionality for the console.

If you want user input, you should use the function raw_input in 2.x and input in 3.x.

Do you want to do a graphical application or a console application?

That will break if the user entered nothing.

I make my user input loops follow this pattern:

[code=PYTHON]

Start a loop that will run indefinitely.

while True:
i = input("Prompt: ")

Here I do my input checking. In this example it checks that i isn't an empty string.
if i:
    #Break out of the indefinite loop.
    break[/code]

I learned it from someone at #python on irc.freenode.net

I like using dictionaries for my multidimensional containers using coordinate tuples as keys. It's not a conventional approach, but despite any disadvantages it has some advantages. For very small or very large coordinates, it has a memory advantage because "coordinates" don't need to exist until they are assigned to. The fact that coordinates can be any hashable objects also presents some interesting options.

griswolf commented: A nice bright light went off over my head. Thanks. +1

Seems to me like it would be good to use both concurrently. I've all ready written a few scripts that can run with both 2.x and 3.x.

Python packages and modules are open source. If you ever want them for a new version you can always refactor the old version. In fact, I think their creators and the community at large would be appreciative of such an effort.

Doing so would be a great opportunity to prove that you are not only a programmer capable of implementing useful Python packages and modules but that you are also well versed in the relevant Python versions.

God I want to smack the creators of some of those courses upside the head with a thick book.

Couple of problems. The first is poor class implementation.

It's OK to make your class without attribute getters and setters. You can access instance attributes by referring to the attributes themselves.

[code]class Car:

def __init__(self, year):
    self.year = year

mycar = Car(1999)
mycar.year[/code]

The second problem with implementation is that you require a speed argument to accelerate and decelerate the car, but inside of those methods you accelerate or decelerate by a constant of 5. Is that desired behavior, or would you rather to accelerate or decelerate by the amount passed as the argument?

The third problem is with your script's structure. You try to create the car before you've gotten the user's input. You must assign identifiers before you can use them elsewhere.

[code]year = raw_input('What year is your car? ')
mycar = car.Car(year)
print mycar.year[/code]

You did a decent job with the class for a beginner. Don't get discouraged. Good luck.

Typecasting the numbers to a string doesn't make much sense to me, but whatever.

You are mistakenly using the sample function.

Here's what you want to do.

[code]import random

def make_secret(numdigits):
a = []
for i in range(numdigits):
a.append(str(random.randrange(0, 10)))
return a[/code]

A technical term for creating a class is 'declare'.

When you create a class you are declaring a class, and when you see a class in code it is a class declaration. Just thought you might want to know the lingo.

b

A quick hack would be something like this:

[code]def run_async(fnc):
def newfnc(*args, **kwargs):
thread = threading.Thread(target=fnc, args = args, kwargs = kwargs)
thread.start()
return newfnc

@run_async
def on_mode(self, connection, event):
if event.arguments() [ 0 ] == "-v":
vname = event.arguments() [ 1 ]
self.connection.mode(channel + " +v", vname)[/code]

Python isn't a bad language, even when it comes to threading.

The 'vibe' I'm getting from the modules you are using is that the objects and process of creating and operating a bot are overly complex.

There isn't much that can be done about that except a rewrite with different design principles, philosophies, and use specifications in mind. (I'm working on an irc bot library at the moment. When I publish the source hopefully it will be more suited for your use and for other people.)

But in the meantime we must make do with what we have here.

Seems like to me you need to add your global handler to an event and that should do the trick.

Doesn't the on_mode method you defined in the bot do what you want?

If so when you initiate your bot you should do something like this I think.

[code]self.add_global_handler("mode", self.on_mode)[/code]

P.S. I posted after you said you needed to add threads.

If you don't mind me asking, what are the "ircbot" and "irclib" modules or packages you imported, and where could we acquire them or view the source?

I'm talking about dotted relative imports.

Try relative imports.

[url]http://www.python.org/dev/peps/pep-0328/#guido-s-decision[/url]

Seem like just the thing. I've used them. They permit you to import modules from a relative parent package.

They're hard to figure out though. The documentation is somewhat lacking so you might have to tinker until you get it right.