0

So whilst ive seen a few infinite loop codes on SO and on the web, i havent seen one the can repeatedly call a method... Here's my code.. and its not working, its just freezes.. Why?

class InfiniteLoop:

    def input():
        print("Hello")
        #num = raw_input("Enter a number: ")
        #print "You entered: ", num

    def loop():
        global input 
        #input = input()
        var = 1
        while var == 1:
            input = input() #

    loop()

Any and all help will be appreciated.. thanks !

EDIT:

class Usb_Check:

def cycle(self):
    buzzer_class = Buzzer()
    lock_class = Lock()
    active = False



    device_re = "Bus \d{,3} Device \d{,3}: ID ([a-f0-9]+:[a-f0-9]+)"

    df = subprocess.check_output("lsusb", shell=True)
    for i in df.split('\n'):
        if i:
                if re.findall(device_re, i, re.I)[0] == key:
                buzzer_class.cycle(2)
14
  • 2
    This is not syntactically valid Python. What's that class doing in the first line? Commented Apr 1, 2014 at 16:53
  • Im extremely new to python.. i usually write PHP or C#, so please forgive me, \but what have i done wrong ? Commented Apr 1, 2014 at 16:54
  • @Thomas, the OP was using tabs instead of spaces for indents. This does not play well with the SO formatter. I fixed that. Commented Apr 1, 2014 at 16:55
  • 1
    To add to @Thomas' comment, even if the class is made valid, this isn't going to freeze, it's going to crash, as after the first call to loop, input will be set to the result of calling input, which, assuming you've actually called self.input and thus not gotten a NameError, will now be None, and therefor not be callable. Edit: Actually, that's not even true... you'll try to call input from the global namespace, so unless it exists outside of class scope, you'll blow up on first run. Commented Apr 1, 2014 at 16:55
  • 1
    @Thomas It's syntactically valid, just thoroughly awful. :) He's creating functions in class definition scope, then calling them from within that scope. It's true that it will create a corrupted instance that will raise an error on calling loop if you ever instantiate InfiniteLoop, but it is technically syntactically valid, and will even run as written. Commented Apr 1, 2014 at 17:09

3 Answers 3

3

I think you're a bit on the confused side about what is actually happening here.

Have you tried pushing enter? I'm guessing you haven't, or you'd get TypeError: 'str' object is not callable

Plainly, you've seen several examples of things on the internet but you haven't really understood what they're doing. Allow me to comment:

The class declaration is not really essential to what you're trying to do here. As a matter of fact, I would probably not worry about using classes until you feel more comfortable with functions, and possibly a thing called scope.

class InfiniteLoop:

Here, you are not passing self in as the first argument. You almost always see this in Python classes because that's really the whole point of using class methods (functions that are declared inside a class).

Also, input() is already the name of a function in Python - this doesn't override the existing function, though, because it's attached to your class InfiniteLoop. And the only way you'll ever[1] be able to call it is via InfiniteLoop.input().

    def input():
        print("Hello")
        #num = raw_input("Enter a number: ")
        #print "You entered: ", num

global input is why I can tell you don't understand scope. This effectively does nothing. The only time you want global is if you're actually going to be assigning values and you want those changes to be visible across your application. It doesn't look like you're trying for that here.

    def loop():
        global input 
        #input = input()

You can actually change this piece to read while var: because 1 is "True". Or better yet, just go with while True:

        var = 1
        while var == 1:
            input = input() #

It's certainly possible to put function calls in the body of your class, but usually you won't see this. Mainly because it's not terribly clear what you are trying to do when that happens. My guess is you just put it here because that was the only way you could get your code to run.

    loop()

If you were trying to write this class-style, then you probably want to write it like so:

class InfiniteLoop:
    def __init__(self):
        self.loop()

    def input(self):
        print("No input here!")

    def loop(self):
        while True:
            self.input()

InfiniteLoop()

Or, better yet you could just write it without the class:

def my_input(): # not input, to avoid shadowing the input() function
    print("Nope, still no input")


def loop():
    while True:
        my_input() # No global necessary, you can see the function from here!

[1]:Not really, but to do anything else is probably just for fun and learning.

Sign up to request clarification or add additional context in comments.

4 Comments

Shit man thanks.. Yeah i understand scope theory and access modifiers and whatnot, was just at the point of trying anything, hence the global call :P And as for the classes, i need them, it is a class in a much bigger project :)
Well, if that's the case then yeah you'll want to use my class-based example ;) As a complete aside, I'd actually look into getting signals when the USB is (un)plugged - there are ways to hook into the system to let it do the checking for you. Event based programming FTW!
Yeah there's not much on the net about it, except the few that i found suggested using HAL and gusb or something.. and apparently HAL is depreciated now.. so it wont work anymore... So any ideas?
I haven't looked at this stuff in forever - but I'd totally recommend checking out software recs
1
class InfiniteLoop():
    def input(self):
        print "Hello"

    def loop(self):
            var =1
            while var == 1:
                self.input()


if __name__ == "__main__":
    A = InfiniteLoop()
    A.loop()

I realize you're new at this, but there are a number of helpful tutorials on the internet for free. You may want to read through them prior to posting on SO. Hope the above code helps you get started.

3 Comments

(Looks like you have broken indentation in your while loop).
Yep thanks. Just recently installed a new text editor(sublime) and had a mix of tabs / spaces. Thanks and fixed.
Thanks guys.. I should be good at this stuff, but PHP is my forte :/ Anyways, i did look for infinite loop tutorials and didnt find much.. But just so i know, can you please explain how the code works ?
0

What's happening

It is not your program that freezes, it is the Python interpreter parser which gets stuck while reading the last line of your program. If you press the Enter key a few times, it gets unstuck and prints this

Traceback (most recent call last):
  File "infiniteloop.py", line 1, in <module>
    class InfiniteLoop:
  File "infiniteloop.py", line 15, in InfiniteLoop
    loop()
  File "infiniteloop.py", line 13, in loop
    input = input() #
  File "<string>", line 0

I am no language lawyer so I cannot tell you what is actually happening there. In a class definition you do have the def function_name(self, param1, param2, ...): construct or that preceeded by an annotation. I do not have a slightest idea what happens if you try to call a function/method there.

What I do know is that judging by what you've probably tried to accomplish you have the syntax wrong.

Syntactically correct version

You have the indentation wrong on your last line. It should not be indented, it is not a part of that class, it should be on the same level as the class declaration.

A syntactically correct version of your program would be this

class InfiniteLoop:
    def input():
        print("Hello")
        #num = raw_input("Enter a number: ")
        #print "You entered: ", num

    def loop():
        global input 
        #input = input()
        var = 1
        while var == 1:
            input = input() #

loop()

Of course, that would not run because there is not a top level function named loop anywhere. But syntax is now right.

The error looks like this

Traceback (most recent call last):
  File "syntax", line 14, in <module>
    loop()
NameError: name 'loop' is not defined

and as to how to fix it you can refer to one of the other answers. Most importantly of all, methods in Python do get their this object (actually self object, as it is customary to call it in Python) explicitly as their first parameter. So you have to declare the methods with def method_name(self, some, other, params):.

What would I do

Keep it simple. Do not declare a class when what you mean is just a couple of functions. And just to make sure, you no not have to declare a class in a Python program.

def get_user_input():
    print("Hello")
    num = raw_input("Write something and press Enter: ")
    return num

def main():
    while True:
        input = get_user_input()
        print "You entered: ", input

if __name__ == '__main__':
    main()

The if __name__ construct is a useful way how to run something if the file is directly executed, but not to run the code if the file is included from some other place.

In conclusion

Read this SO question, answers, and the free to read Dive into Python book that is recommended there Learning Python coming from PHP ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.