Variable Seems to Reset

  • (2 Pages)
  • +
  • 1
  • 2

28 Replies - 3416 Views - Last Post: 21 September 2012 - 02:34 AM Rate Topic: -----

#1 Gamegoofs2  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 159
  • Joined: 15-April 09

Variable Seems to Reset

Posted 17 September 2012 - 02:50 PM

I'm guessing this is really a simple fix and that it's just my lack of Python knowledge.

I want the program to keep running until the condition is met, but the global variable I have to control this seems to reset after I've run through the script once.

Here's my code:
from bs4 import BeautifulSoup
import urllib, re, winsound, time

url = 0
deal = 0

def main():
	url = raw_input("Please enter url to watch: ")
	deal = raw_input("Please enter the percent: ")
	
	control(url, deal)
	print "Done"

def control(addr, dealz):
	html = watcher(addr)
	percent = regex(html)
	if percent >= dealz:
		playNoise()
		return
	else:
		print "Not yet..."
		time.sleep(10)
		control(url, deal)
	
def watcher(addr):
	print addr
	sock = urllib.urlopen(addr)
	html = sock.read()
	sock.close()
	
	soup = BeautifulSoup(html)
	
	percent = soup.find_all(id="productYoyo_Relative")
	for item in percent:
		product = str(item)
	
	return product
	
def regex(product):
	p = re.compile('.*-?(\d{2})%.*')
	result = p.match(product)
	return result.group(1)

def playNoise():
	winsound.PlaySound('alert.wav', winsound.SND_FILENAME)
	
	
if __name__ == "__main__":
	main()



url keeps getting reset to 0 after I've given it the value.

Is This A Good Question/Topic? 0
  • +

Replies To: Variable Seems to Reset

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2101
  • View blog
  • Posts: 3,204
  • Joined: 21-June 11

Re: Variable Seems to Reset

Posted 17 September 2012 - 03:00 PM

You need to use the global keyword if you want to assign to global variables from within a function. Otherwise a line like foo = bar will create a local variable foo that only exists within that method - even if there already is a global variable that's also named foo.

So without using global the line url = raw_input(...) in your main function does not at all affect the value of the global variable url, which stays 0. Same for deal.

That said, you shouldn't be using global variables at all here (or ever). Why don't you just keep using addr and dealz in url?
Was This Post Helpful? 2
  • +
  • -

#3 Gamegoofs2  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 159
  • Joined: 15-April 09

Re: Variable Seems to Reset

Posted 17 September 2012 - 03:11 PM

What do you mean by keep using addr and dealz in url?

I'm rather new to Python, why is it bad to use global variables?
Was This Post Helpful? 0
  • +
  • -

#4 Simown  Icon User is offline

  • Blue Sprat
  • member icon

Reputation: 319
  • View blog
  • Posts: 650
  • Joined: 20-May 10

Re: Variable Seems to Reset

Posted 17 September 2012 - 03:18 PM

It's not just Python, it's programming in general. They are considered bad practice because of loss of locality, basically, they can be modified from anywhere, they can be used anywhere, they can be overwritten anywhere, and probably lead to a lot of confusion and bugs.

Not sure... but I think he means, why are they global in the first place? Can't you keep them local to functions and pass them as parameters (which you are anyway)?

This post has been edited by Simown: 17 September 2012 - 03:20 PM

Was This Post Helpful? 3
  • +
  • -

#5 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2101
  • View blog
  • Posts: 3,204
  • Joined: 21-June 11

Re: Variable Seems to Reset

Posted 17 September 2012 - 03:53 PM

View PostGamegoofs2, on 18 September 2012 - 12:11 AM, said:

What do you mean by keep using addr and dealz in url?


I meant "keep using addr and dealz in control". Sorry for the typo.
Was This Post Helpful? 0
  • +
  • -

#6 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5800
  • View blog
  • Posts: 12,636
  • Joined: 16-October 07

Re: Variable Seems to Reset

Posted 17 September 2012 - 04:15 PM

This is NOT the way to do a loop:
def control(addr, dealz):
	html = watcher(addr)
	percent = regex(html)
	if percent >= dealz:
		playNoise()
		return # ok, you actually don't need it
	else:
		print "Not yet..."
		time.sleep(10)
		control(url, deal) # what is deal?  Why?!?



Instead:
def control(addr, dealz):
	while True: # loop until we leave from the inside
		# if you use the result once
		# then you don't need to assign it to a variable
		if regex(watcher(addr)) >= dealz:
			playNoise()
			return # now this makes sense
		# made it here, we'll go for another spin
		print "Not yet..."
		time.sleep(10)
		# go back up to the top of the while



Hope this helps.
Was This Post Helpful? 1
  • +
  • -

#7 Gamegoofs2  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 159
  • Joined: 15-April 09

Re: Variable Seems to Reset

Posted 17 September 2012 - 05:35 PM

Great! I got it working thanks guys.

Kinda off topic, but in Java wouldn't you have global variables but only change them or get their value with getter and setter methods?

i.e.
private int foo;

public int fooSet(bar) {
    foo = bar;
}
public int fooGet() {
    return foo;
}



@baavgai
You're right! I have no clue what I was thinking. Just goes to show how rusty I've gotten over the summer.

This post has been edited by Gamegoofs2: 17 September 2012 - 05:38 PM

Was This Post Helpful? 0
  • +
  • -

#8 Simown  Icon User is offline

  • Blue Sprat
  • member icon

Reputation: 319
  • View blog
  • Posts: 650
  • Joined: 20-May 10

Re: Variable Seems to Reset

Posted 17 September 2012 - 06:00 PM

That's debatable I'd say. But in my opinion, no.

Your example is a little disjoint from your question:
private int foo

This variable is not global, it's local to the class it's in.

If it was global it would be:
public int foo

And then you wouldn't need getters and setters to call it from any class at all! The whole thing comes back to not being able to modify them without intent, or erroneously. To access the foo variable you must use the getters and setters, and there is no real way of accidentally using it without calling fooGet or fooSet explicitly.

When the code isn't even in a class, it makes even less sense. As all Java code is in a class, then it usually makes sense there.

An example of a class where it might make sense:
class myClass(object):

   # The constructor
   def __init__(self):
        self.foo = None

   def setFoo(self, x):
      self.foo = x

   def getFoo(self):
      return self.foo


A problem with Python can be that things can never really be private. You can't restrict yourself as much, so you need to build constructs around your data to prevent illegal access, and save you a headache in the long run :)

This post has been edited by Simown: 17 September 2012 - 06:03 PM

Was This Post Helpful? 1
  • +
  • -

#9 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5800
  • View blog
  • Posts: 12,636
  • Joined: 16-October 07

Re: Variable Seems to Reset

Posted 18 September 2012 - 05:57 AM

Well, within Java, global is a little more academic. There is no real global context, everything belongs to a class. Within an object, object level variables are often considered global within the context of the instance. It is standard practice expose instance variables with getters and setters.

I disagree that public int foo; means global in Java. Rather, it means an object variable is exposed and can be manipulated external to the object. In Java, the closest thing you'd have to a global is public static int foo; where the variable belongs to the class and is accessible to all code, all the time.

In Python, as in Java, as in pretty much any programming language, controlling and limiting scope of variables is a discipline required to be a good programmer.
Was This Post Helpful? 2
  • +
  • -

#10 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7644
  • View blog
  • Posts: 12,890
  • Joined: 19-March 11

Re: Variable Seems to Reset

Posted 18 September 2012 - 06:54 AM

View PostGamegoofs2, on 17 September 2012 - 07:35 PM, said:

Kinda off topic, but in Java wouldn't you have global variables but only change them or get their value with getter and setter methods?


We probably shouldn't go too far down the java rabbit hole, but here goes.
You might have "global" variables at the class level, and you might expose them with getters and setters, but you shouldn't. A class is a tool for encapsulating data such that the data is associated with the methods which manipulate it. The internals of a class should remain internal to it. The correct number of getters and setters in a given class is zero.

Bringing this back to python, one of the issues I've had with python is the lack of encapsulation. It seems to me that if you define an object, there is no way to achieve data hiding. However, I really have almost no experience in actually working with python - just got started in it this summer - so this is likely me missing something. Can anyone clarify this situation for me?
Was This Post Helpful? 0
  • +
  • -

#11 Gamegoofs2  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 159
  • Joined: 15-April 09

Re: Variable Seems to Reset

Posted 18 September 2012 - 08:02 AM

Quote

The correct number of getters and setters in a given class is zero.

I disagree. Having getters and setters allows you to control the interactions with the variable.

Say you have a variable that needs a specifically formatted string. Having a setter would filter our bad data or even correct the data before inserting it into the variable. Like wise for getters is the data isn't readable to humans then the getter could return comprehensible or useful data. But I digress.
Was This Post Helpful? 1
  • +
  • -

#12 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7644
  • View blog
  • Posts: 12,890
  • Joined: 19-March 11

Re: Variable Seems to Reset

Posted 18 September 2012 - 08:10 AM

View PostGamegoofs2, on 18 September 2012 - 10:02 AM, said:

Quote

The correct number of getters and setters in a given class is zero.

I disagree. Having getters and setters allows you to control the interactions with the variable.

Say you have a variable that needs a specifically formatted string. Having a setter would filter our bad data or even correct the data before inserting it into the variable. Like wise for getters is the data isn't readable to humans then the getter could return comprehensible or useful data. But I digress.


Don't misunderstand me, a set method is infinitely preferable to a public field, for exactly the reason you suggest. However, I can't think of a lot of cases where I need to reach into an actual class and fiddle with its data at all, whether in a controlled fashion or willy-nilly. That seems to me a violation of basic object-oriented design.
Was This Post Helpful? 1
  • +
  • -

#13 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5800
  • View blog
  • Posts: 12,636
  • Joined: 16-October 07

Re: Variable Seems to Reset

Posted 18 September 2012 - 08:13 AM

View Postjon.kiparsky, on 18 September 2012 - 09:54 AM, said:

It seems to me that if you define an object, there is no way to achieve data hiding.


This is 100% correct!

I understand your issue. I like all my classes well hidden, const correct, strictly typed... perhaps compulsively so. Python spits on all this.

There are a few conventions for hiding things. The underscore is said to equate to protected. The double underscore to private. The double underscores do mangle the name slightly with the class name. Mostly to avoid namespace collision:

>>> class Foo():
...     def m1(self):
...             pass
...     def _m2(self):
...             pass
...     def __m3(self):
...             pass
... 
>>> dir(Foo)
['_Foo__m3', '__doc__', '__module__', '_m2', 'm1']
>>> 



There are a number of serious attempts to hide things that are more or less successful. You can screw with dict, have something like a C++ pimpl, do a lot of function in function embedding... Ultimately, it's all programmers from other languages trying to make python be less pythony.

The no hiding thing is very intentional, will not change, and follows the strange Python philosophy of: "we're all consenting adults here"

Here's a pretty good collection of pythonisms here.

Once you settle into a pants down, tuple tossing, duck typed world of Python, it's actually rather freeing. Hiding everything with an iron fist just seems like overkill. A class for everything seems like a waste of effort.
Was This Post Helpful? 2
  • +
  • -

#14 Simown  Icon User is offline

  • Blue Sprat
  • member icon

Reputation: 319
  • View blog
  • Posts: 650
  • Joined: 20-May 10

Re: Variable Seems to Reset

Posted 18 September 2012 - 08:17 AM

I agree with the previous post; you can validate and manipulate your own data when getting and setting without having to do it in the calling class, and the manipulation of the data is encapsulated within the class it comes from.

Even though you can't hide Python data, I usually program in Python like I would do in Java, and use the variables inside the class and use accessors to access the variables outside.

Edit: baavgai beat me to it, and with a better explanation about "private variables". What he said ^

Edit again: Ok, I understand what jon.kiparsky is getting at now. You guys post too quickly for my liking!

This post has been edited by Simown: 18 September 2012 - 08:22 AM

Was This Post Helpful? 0
  • +
  • -

#15 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7644
  • View blog
  • Posts: 12,890
  • Joined: 19-March 11

Re: Variable Seems to Reset

Posted 18 September 2012 - 08:27 AM

Quote

A class for everything seems like a waste of effort.


Sure, but when I want a class, I'd like it to be a class. The "we're all consenting adults" slogan seems to miss the point, doesn't it? I mean, we might have a houseful of consenting adults, but that doesn't mean I won't ever want to close my bedroom door.

Getting out of the sticky world of metaphor, this seems more like laziness than philosophy to me. The reasons for private access are good ones: it increases modularity and decreases chances for bugs. I don't see the arguments for global access - we wouldn't want to advise a Java programmer to use only public access, would we?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2