todolist = []  def add_item(item):     todolist =  todolist + [item]  def main():      add_item(1)      print(todolist)   if __name__ == '__main__':     main()   I am trying to make a function called add_item() which works like append() and I am not allowed to use any built in functions. I keep getting an UnboundLocalError. How would I fix this?
4613
How can I create or use a global variable in a function?  If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
1360
I want to create a list of lambda objects from a list of constants in Python; for instance:  listOfNumbers = [1,2,3,4,5] square = lambda x: x * x listOfLambdas = [lambda: square(i) for i in listOfNumbers]   This will create a list of lambda objects, however, when I run them:  for f in listOfLambdas:     print f(),   I would expect that it would print  1 4 9 16 25   Instead, it prints:  25 25 25 25 25   It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.  EDIT: a bit more of trying things and such came up with this:  listOfLambdas = [] for num in listOfNumbers:     action = lambda: square(num)     listOfLambdas.append(action)     print action()   Prints the expected squares from 1 to 25, but then using the earlier print statement:  for f in listOfLambdas:     print f(),   still gives me all 25s. How did the existing lambda objects change between those two print calls?  Related question:
97268
I am creating a bone, and then a collection with a specific name if it does not exist, with the following function: def make_collection(collection_name):     if collection_name in bpy.data.collections:         return bpy.data.collections[collection_name]     else:         new_collection = bpy.data.collections.new(collection_name)         bpy.context.scene.collection.children.link(new_collection)         return new_collection  The collection is linked to the master collection so it's on the top of the hierarchy, and now i try link it to the collection. I create the collection: root = make_collection(&quot;bat&quot;)  and later on in the code, i create a bone (although is an empty since it's a standalone bone), and i try to link it like this: bpy.ops.object.empty_add(type='CUBE') bone = bpy.context.active_object bone.name = data[i].name #bpy.ops.collection.objects_add_active(collection=root) root.objects.link(bone)  Even though it's called root, root is not the master collection, just to clarify. The result is the following:  It's the same empty i created, that appears twice in both collections. Although an idea would be to just delete other collections, 2 will appear still, one in the master collection, and one in the collection i created. Also it's the same item since, if i click one, both get selected at the same time, so there's only one empty in the scene, i just can choose where to click it from. Now the problem is i'm doing this with several objects in a loop, so i  would be basically duplicating the object list twice, and that's pretty redundant. If i don't use the root.objects.link code at all, the objects would just be on the master collection, but i want them to be on the collection i specifically created. Is there any way to fix this? I'm not sure why it appears on both collections and i'm very confused. I'm fairly new with the blender API, so i'm not sure what i'm doing wrong. Thanks for reading!
18288
I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this: import unittest  l = [[&quot;foo&quot;, &quot;a&quot;, &quot;a&quot;,], [&quot;bar&quot;, &quot;a&quot;, &quot;b&quot;], [&quot;lee&quot;, &quot;b&quot;, &quot;b&quot;]]  class TestSequence(unittest.TestCase):     def testsample(self):         for name, a,b in l:             print &quot;test&quot;, name             self.assertEqual(a,b)  if __name__ == '__main__':     unittest.main()  The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?
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?
54890
I'm trying to used the Python syntax in ArcGIS 10's field calculator and am thoroughly confused. So far the most basic calculations are failing me, and I don't understand why. I'm trying to create a function to just set the values of all cells in a column to be a multiple of the argument that I pass in ( I wanted to try something simple to test it out, as anything more complicated I tried also failed).   However, the error messages are telling me that my syntax is incorrect:    but I can't understand what is incorrect.     As an aside, I'm also horrified at how hard it is to write readable python in the field calculator box as there is no syntax highlighting, or clear indentation. It would be quicker, and easier to write an external Python script to do this calculation, but I want to try to figure out how this new function worked within the program.
52498
I am running into an error. I have a set of functions which I want to import in the python Add-In script at the time of execution, but when I built Add-In with "import stats" line then tools are unresponsive. Any suggestions whether it is possible to import functions in the Add-In script?  import arcpy import os import pythonaddins import stats  optfolder = "C:/temp"  class AoI(object): """Implementation for rectangle_addin.tool (Tool)"""     def __init__(self):         self.enabled = True         self.cursor = 5         self.shape = 'Rectangle'         os.makedirs(optfolder)      def onRectangle(self, rectangle_geometry):    """Occurs when the rectangle is drawn and the mouse button is released.     The rectangle is a extent object."""          extent = rectangle_geometry         arcpy.Clip_management(r'C:/temp/ras', "%f %f %f %f" %(extent.XMin, extent.YMin, extent.XMax, extent.YMax),                               optfolder + '/ras1', "#", "#", "NONE")         arcpy.RefreshActiveView()
4188
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:  flist = []  for i in xrange(3):     def func(x): return x * i     flist.append(func)  for f in flist:     print f(2)   Note that this example mindfully avoids lambda. It prints "4 4 4", which is surprising. I'd expect "0 2 4".   This equivalent Perl code does it right:  my @flist = ();  foreach my $i (0 .. 2) {     push(@flist, sub {$i * $_[0]}); }  foreach my $f (@flist) {     print $f-&gt;(2), "\n"; }   "0 2 4" is printed.  Can you please explain the difference ?    Update:   The problem is not with i being global. This displays the same behavior:  flist = []  def outer():     for i in xrange(3):         def inner(x): return x * i         flist.append(inner)  outer() #~ print i   # commented because it causes an error  for f in flist:     print f(2)   As the commented line shows, i is unknown at that point. Still, it prints "4 4 4".
103588
In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:  "[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]"   Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:  print 'my list is %s'%(list)   it looks something like this:  [&lt;__main__.cell instance at 0x2a955e95f0&gt;, &lt;__main__.cell instance at 0x2a955e9638&gt;, &lt;__main__.cell instance at 0x2a955e9680&gt;]   how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?
13837
I'm searching a way to append a group in Python.  It should behave exactly like the Append function (ShiftF1) works, all objects should be local and editable. The idea is to append a character (with rig etc.) via Python and not Link it (to be able to modify it without making everything local one by one).  Thanks
27323
I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.  At the moment the only way I can find to do this is like:  mat = None for col in columns:     if mat is None:         mat = col     else:         mat = hstack((mat, col))   Whereas if it were a list, I'd do something like this:  list = [] for item in data:     list.append(item)   Is there a way to use that kind of notation for  arrays or matrices?
2370
How can I bind arguments to a Python method to store a nullary functor for later invocation?  Similar to C++'s boost::bind.  For example:  def add(x, y):     return x + y  add_5 = magic_function(add, 5) assert add_5(3) == 8
87827
I created a utility function to return the expected single item from an generator expression  print one(name for name in ('bob','fred') if name=='bob')   Is this a good way to go about it?  def one(g):     try:         val = g.next()         try:             g.next()         except StopIteration:             return val         else:             raise Exception('Too many values')     except StopIteration:         raise Exception('No values')
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()
53456
What is the difference between:  some_list1 = [] some_list1.append("something")   and  some_list2 = [] some_list2 += ["something"]
29305
What does it mean to extend a function? Can someone please give an example?  Thanks in advance!
15061
Passing an undimensioned array to the VB6's Ubound function will cause an error, so I want to check if it has been dimensioned yet before attempting to check its upper bound.  How do I do this?