0

I found a very strange thing in Python. When trying to access an ordinary object (like int, float, etc.) from some function it's asking me to define the variable to be a global variable.

But when I tried to do the same with Queue the result was different; in that situation I could approach the Queue from the function even when I didn't make it global.

How can some objects act like globals (Queue, for example) and some others not (like int, string, etc.)?

I clear myself: Here is two code samples: some def:

def some_def():
    q.put(1)

some main:

q = Queue.Queue()

On the other object: some def:

def some_def():
    number += 1

some main:

number = 0

The two different code samples will act each one different way: The first one will put the value in the Queue, while the second will throw an Error because 'number' is not a global variable.

dfsfg sfg
  • 77
  • 1
  • 9
  • please show minimal code samples with full stack traces – Craig Burgler Sep 17 '16 at 21:13
  • As mentioned, please post the code in question – idjaw Sep 17 '16 at 21:14
  • You're confusing two different things: mutable and immutable objects. If you reassigned a name that pointed to something mutable (like a queue, list, dictionary, ...) you'd get the same behaviour as reassigning an integer or string. It's only when you *mutate* the mutable (e.g. `list.append`) that you can change the state of a "global" object. – jonrsharpe Sep 17 '16 at 21:14
  • See also http://stackoverflow.com/q/4630543/3001761, http://nedbatchelder.com/text/names.html, ... – jonrsharpe Sep 17 '16 at 21:16
  • @Craig Burgler edited – dfsfg sfg Sep 17 '16 at 22:09
  • @jonrsharpe I dont think its my issue. see the editing i did and tell me if its the issue you talk about – dfsfg sfg Sep 18 '16 at 10:57
  • @dfsfgsfg it's exactly the same. You are *mutating* `q` using its `put` method, **not** assigning a new value to the name. – jonrsharpe Sep 18 '16 at 10:58
  • @jonrsharpe if i understood right - in python, if i bind between a name and a mutable object, then i can use that name in function that i didnt bind this name in there scope. why python act like this? – dfsfg sfg Sep 18 '16 at 20:17
  • @jonrsharpe i mean - why does python act in another way to objects that have method call? in the link you sent me the guy saied: "because nothing local shadows them." but it doesnt saied anything to me... – dfsfg sfg Sep 18 '16 at 20:35
  • It's not clear to me what you still don't understand. There's no *"act in another way"* and there's plenty of material out there on Python's naming and binding model. I can onto suggest that you read more of it. – jonrsharpe Sep 18 '16 at 21:10

0 Answers0