I am making a Python Discord bot with discord.py. I am relatively new to Python but have about eight years of experience with other languages. My problem is that I get the UnboundLocalError: local variable 'prefix' referenced before assignment even though I have defined prefix as a global variable. (I am using Python 3.6.8)  I have tried defining the variables outside the on_ready function, but I get the same result.  import discord;  client = discord.Client();  @client.event async def on_ready():   print('Loading complete!')   ...   global prefix   prefix = 'hello world'  @client.event async def on_message(message):    if message.author == client.user:     return    messageContents = message.content.lower()   splitMessage = messageContents.split()   try:     splitMessage[0] = splitMessage[0].upper()lower()   except:     return   if splitMessage[0]==prefix:     ...     (later in that if statement and a few nested ones)     prefix = newPref  client.run('token')   I expected the output would be that it runs the code within the if statement, but instead I get the error UnboundLocalError: local variable 'prefix' referenced before assignment and no code is run.  The only thing I can think of being the problem is prefix = newpref. I tried:  global prefix prefix = newpref   But then I got the error: SyntaxError: name 'prefix' is used prior to global declaration and the bot didn't start at all. What should I do?
1022
The following code works as expected in both Python 2.5 and 3.0:  a, b, c = (1, 2, 3)  print(a, b, c)  def test():     print(a)     print(b)     print(c)    # (A)     #c+=1       # (B) test()   However, when I uncomment line (B), I get an UnboundLocalError: 'c' not assigned at line (A). The values of a and b are printed correctly. This has me completely baffled for two reasons:   Why is there a runtime error thrown at line (A) because of a later statement on line (B)? Why are variables a and b printed as expected, while c raises an error?   The only explanation I can come up with is that a local variable c is created by the assignment c+=1, which takes precedent over the "global" variable c even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.  Could someone please explain this behavior?
98249
While working on a C++ project, I was looking for a third party library for something that is not my core business. I found a really good library, doing exactly what's needed, but it is written in Python. I decided to experiment with embedding Python code in C++, using the Boost.Python library.  The C++ code looks something like this:  #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;boost/python.hpp&gt;  using namespace boost::python;  int main(int, char **)  {     Py_Initialize();      try      {         object module((handle&lt;&gt;(borrowed(PyImport_AddModule("__main__")))));          object name_space = module.attr("__dict__");         object ignored = exec("from myModule import MyFunc\n"                           "MyFunc(\"some_arg\")\n",                           name_space);          std::string res = extract&lt;std::string&gt;(name_space["result"]);     }      catch (error_already_set)      {         PyErr_Print();     }      Py_Finalize();     return 0; }   A (very) simplified version of the Python code looks like this:  import thirdparty  def MyFunc(some_arg):     result = thirdparty.go()     print result   Now the problem is this:  'MyFunc' executes fine, i can see the print of 'result'. What i cannot do is read 'result' back from the C++ code. The extract command never finds 'result' in any namespace. I tried defining 'result' as a global, i even tried returning a tuple, but i cannot get it to work.
19595
I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?  (I'm not asking about $('p.foo') syntax that you see in jQuery and others, but normal variables like $name and $order)
30442
Consider the following code:    def CalcSomething(a):     if CalcSomething._cache.has_key(a):       return CalcSomething._cache[a]     CalcSomething._cache[a] = ReallyCalc(a)     return CalcSomething._cache[a]   CalcSomething._cache = { }   This is the easiest way I can think of for simulating a 'local static' variable in python. What bothers me is that CalcSomething._cache is mentioned outside the function's definition, but the alternative would be something like that:    if not hasattr(CalcSomething, "_cache"):       setattr(CalcSomething, "_cache", { } )     inside the function's definition, which is really cumbersome.    Is there a more elegant way?    [EDIT] Just to clarify, this question is not about local function caches, as the example above might suggest. Here is another short example where a 'static local' might be handy:    def ParseString(s):     return ParseString._parser.parse(s)   # Create a Parser object once, which will be used for all parsings. # Assuming a Parser object is heave on resources, for the sake of this example. ParseString._parser = Parser()
53471
Now that it's clear , there is an associated concept that I use all the time without knowing what it really means.   I suppose everybody made once a mistake with parenthesis, resulting  in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for.  Could you give me some explanations, including examples with the magic method ?
109435
What is the syntax and which namespace/class needs to be imported? Give me sample code if possible. It would be of great help.
6080
I'm new to both JavaScript and . In YUI library examples, you can find many uses of this construct:  (function() {     var Dom = YAHOO.util.Dom,     Event = YAHOO.util.Event,     layout = null,         ... })();   I think the last couple of parentheses are to execute the function just after the declaration.  ... But what about the previous set of parentheses surrounding the function declaration?  I think it is a matter of scope; that's to hide inside variables to outside functions and possibly global objects. Is it? More generally, what are the mechanics of those parentheses?
37330
I am trying to get a number by counting how many points are in a shapefile. And this works, except I then am running into trouble using that number somewhere else. Eventually, I'll be using that count in some math (field calculator), but while debugging I'm running into an error that will end up causing me trouble later on.   This code:  TotalPoints = arcpy.GetCount_management(Path_Pts) arcpy.AddMessage("&gt;&gt;&gt;&gt; PROCESS: COUNT PATH POINTS {" + TotalPoints + "}")   gives this error:  TypeError: cannot concatenate 'str' and 'Result' objects   I tried casting it as a int, which it ALSO doesn't like:  TypeError: int() argument must be a string or a number, not 'Result'   So I've got a 'Result' object and need to turn it into a number.   How can I do that -- or is using the ArcPy function unnecessary or overly complicated here?
46504
I want to create a command that changes its output the second time it gets called. For example, I want it to yield 1 the first time it's called, and 2 the second time:  \newcommand\mycommand { do stuff } \mycommand % yields 1 \mycommand % yields 2   My idea was to define a global variable, something like \hasbeencalled, and globally redefine that variable if the command has been called. Something like:  \def\hasbeencalled{0} \newcommand\mycommand[1] {     \ifnum\hasbeencalled=0         1         \global\def\hasbeencalled{1}     \else          2     \fi }   But this doesn't work. Somehow the global redefinition happens retroactively and changes it so that I get the output  \mycommand % yields 2 \mycommand % yields 2   But if I take away the \global, then I get   \mycommand % yields 1 \mycommand % yields 1   What can I do?
20532
Possible Duplicate:          I understand that the @ symbol can be used before a string literal to change how the compiler parses the string.  But what does it mean when a variable name is prefixed with the @ symbol?
29326
Here is my test code and picture:  import bpy   # Simple property reading/writing from ID properties. # This is what the RNA would do internally. def get_float(self):     return self["testprop"]   def set_float(self, value):     self["testprop"] = value  #bpy.types.Scene.test_float = bpy.props.FloatProperty(get=get_float,set=set_float) bpy.types.Scene.test_float = bpy.props.FloatProperty()   bpy.context.scene.test_float = 12.34     When I don't explicitly set the "get/set" function for my property, after assigning the value, I can get the property value by 'scene["test_float"]', but if I explicitly set the "get/set" function, then if I try to type in the same commands, I will receive a error "KeyError: 'bpy_struct[key]: key "test_float" not found'" . So what should I do to get the same results by using explicitly  "get/set" function?
4541
When I compile the Python code below, I get      IndentationError: unindent does not match any outer indentation level     import sys  def Factorial(n): # Return factorial     result = 1     for i in range (1,n):         result = result * i     print "factorial is ",result     return result   Why?
108454
I try to do this:  bpy.ops.object.select_all() bpy.ops.object.join()   in my script. It selects all the stuff like CtrlA but fails on join() (CtrlJ) with the following error message:     Traceback (most recent call last):   File "", line 1,   in    File "C:\Program Files\Blender   Foundation\Blender\2.71\scripts\modules\bpy\ops.py", line 188, in   __ call __       ret = op_call(self.idname_py(), None, kw) RuntimeError: Operator bpy.ops.object.join.poll() failed, context is incorrect   the message is from console.  How can I make this work? CtrlA, CtrlJ actually works.
65193
Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures.    Some limitations are mentioned in the  (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.  Seeing a code example for a concrete limitation would be great.  Related questions:
7441
Was there any reason why the designers of Java felt that local variables should not be given a default value? Seriously, if instance variables can be given a default value, then why can't we do the same for local variables?  And it also leads to problems as explained in :     Well this rule is most frustrating when trying to close a resource in a finally block. If I instantiate the resource inside a try, but try to close it within the finally, I get this error. If I move the instantiation outside the try, I get another error stating that a it must be within a try.      Very frustrating.
69514
In Python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals().  Is there some equivalent way of doing this in Javascript?  For instance, I would like to do something like the following:  var foo = function(){ alert('foo'); }; var bar = function(){ alert('bar'); };  var s = 'foo'; locals()[s](); // alerts 'foo'   Is this at all possible, or should I just be using a local object for the lookup?
24071
I'm trying to understand Python's approach to variable scope. In this example, why is f() able to alter the value of x, as perceived within main(), but not the value of n?  def f(n, x):     n = 2     x.append(4)     print('In f():', n, x)  def main():     n = 1     x = [0,1,2,3]     print('Before:', n, x)     f(n, x)     print('After: ', n, x)  main()   Output:  Before: 1 [0, 1, 2, 3] In f(): 2 [0, 1, 2, 3, 4] After:  1 [0, 1, 2, 3, 4]