this is my attempt in python 3.4:  import imp  def my_example_function():   print("my_example_function:")  class my_class:   def __init__(self):     module = imp.load_source(my_example_function, __file__)  my_class_instance = my_class()   result is:  Traceback (most recent call last):   File "D:\Python34\test.py", line 10, in &lt;module&gt;     my_class_instance = my_class()   File "D:\Python34\test.py", line 8, in __init__     module = imp.load_source(my_example_function, __file__)   File "D:\python34\lib\imp.py", line 166, in load_source     spec = util.spec_from_file_location(name, pathname, loader=loader)   File "&lt;frozen importlib._bootstrap&gt;", line 932, in spec_from_file_location   File "&lt;frozen importlib._bootstrap&gt;", line 1439, in is_package AttributeError: 'function' object has no attribute 'rpartition'   It looks like some kind of internal error a bug in python itself.
6666
I've read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python.   I understand that it's not always good to do so. But how might one do this?
67782
As part of an existing add-on, I'm trying to create an object and add it to the scene using Python. I followed a Blender Cookbook tutorial found here: . I use the following code to do so:  emptyMesh = bpy.data.meshes.new('emptyMesh') theObj = bpy.data.objects.new("object_name", emptyMesh) bpy.context.scene.objects.link(theObj)   But I get the following error when I try to link theObj to the scene objects:  AttributeError: 'bpy_prop_collection' object has no attribute 'link'   This works just fine in Blender 2.76-2.79, but doesn't work in the 2.80 test build I downloaded. Was there a change to the Python API? Or is this maybe a bug in the test build?
11039
Imagine this directory structure:  app/    __init__.py    sub1/       __init__.py       mod1.py    sub2/       __init__.py       mod2.py   I'm coding mod1, and I need to import something from mod2. How should I do it?    I tried from ..sub2 import mod2 but I'm getting an "Attempted relative import in non-package".  I googled around but found only "sys.path manipulation" hacks. Isn't there a clean way?      Edit: all my __init__.py's are currently empty    Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (sub1, subX, etc.).  Edit3: The behaviour I'm looking for is the same as described in  (thanks John B)
31376
I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?  Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of  import foo from bar.baz import quux  def myFunction():     foo.this.that(quux)   I move all my imports into the function where they're actually used., like this:  def myFunction():     import foo     from bar.baz import quux      foo.this.that(quux)   This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.  Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.
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.
11658
Python is installed in a local directory.    My directory tree looks like this:  (local directory)/site-packages/toolkit/interface.py   My code is in here:  (local directory)/site-packages/toolkit/examples/mountain.py   To run the example, I write python mountain.py, and in the code I have:  from toolkit.interface import interface   And I get the error:  Traceback (most recent call last):   File "mountain.py", line 28, in ?     from toolkit.interface import interface ImportError: No module named toolkit.interface   I have already checked sys.path and there I have the directory /site-packages. Also, I have the file __init__.py.bin in the toolkit folder to indicate to Python that this is a package. I also have a __init__.py.bin in the examples directory.  I do not know why Python cannot find the file when it is in sys.path.  Any ideas?  Can it be a permissions problem?  Do I need some execution permission?
7012
In Python 2.5, the following code raises a TypeError:  &gt;&gt;&gt; class X:       def a(self):         print "a"  &gt;&gt;&gt; class Y(X):       def a(self):         super(Y,self).a()         print "b"  &gt;&gt;&gt; c = Y() &gt;&gt;&gt; c.a() Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt;   File "&lt;stdin&gt;", line 3, in a TypeError: super() argument 1 must be type, not classobj   If I replace the class X with class X(object), it will work. What's the explanation for this?
2689
What is the idiomatic Python equivalent of this C/C++ code?  void foo() {     static int counter = 0;     counter++;     printf("counter is %d\n", counter); }   specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
94067
I can't find a definitive answer for this. As far as I know, you can't have multiple __init__ functions in a Python class. So how do I solve this problem? Suppose I have a class called Cheese with the number_of_holes property. How can I have two ways of creating cheese objects...  One that takes a number of holes like this: parmesan = Cheese(num_holes = 15) And one that takes no arguments and just randomizes the number_of_holes property: gouda = Cheese()  I can think of only one way to do this, but this seems clunky: class Cheese():     def __init__(self, num_holes = 0):         if (num_holes == 0):             # Randomize number_of_holes         else:             number_of_holes = num_holes  What do you say? Is there another way?
18926
I'm trying to understand the use of super(). From the looks of it, both child classes can be created, just fine.   I'm curious to know about the actual difference between the following 2 child classes.  class Base(object):     def __init__(self):         print "Base created"  class ChildA(Base):     def __init__(self):         Base.__init__(self)  class ChildB(Base):     def __init__(self):         super(ChildB, self).__init__()  ChildA()  ChildB()
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()
108414
I am loosing my mind here.   Every example addon in blender uses bpy.types.INFO_MT_file_export yet not a single doc explains where the hell the name INFO_MT_file_export comes from.  The doc for bpy.types doesn’t have anything about it. Which leads me to believe we are accessing some object.  I can draw the conclusion that it’s a bl_idname for the info menu and the export submenu, but I don’t understand why we can access it using the dot operator inside of bpy.types, or why we can call the append and remove function if it’s a type of Menu.  Moreover, is there a list or something of all of these predefined possible menu ids?
17232
Hi i'm thying threading with bpy this is my code:  import bpy import threading   class Cubes(threading.Thread):      def __init__(self):         threading.Thread.__init__(self)       def run(self):          scale = 0.2         space = 0.2         max_range = 6           for i in range(0, max_range):              bpy.ops.mesh.primitive_cube_add(radius = 1, location=(0, 0, 1))             bpy.ops.object.origin_set( type="ORIGIN_CURSOR" )              bpy.context.active_object.scale.x = scale             bpy.context.active_object.scale.y = scale             bpy.context.active_object.scale.z = 5              bpy.ops.object.transform_apply(location = False, rotation = False, scale = True)             bpy.context.active_object.location = (((i*scale*2)+(i*space))-(((max_range*scale*2)+(max_range*space)))/2,0,0)           return  t = Cubes() t.start()   but when i run this the console give me this error:  Exception in thread Thread-1: Traceback (most recent call last):   File "C:\Program Files\Blender Foundation\Blender\2.75\python\lib\threading.py", line 921, in _bootstrap_inner     self.run()   File "C:\Users\Davide\Desktop\Sound_Visualizer.blend\Sound_Visualizer_Circular.py", line 40, in run AttributeError: 'Context' object has no attribute 'active_object'   Can someone help me?
55914
I'm trying to put together an add-on that contains two operators.  I've gotten each operator file to run properly independently, but I'm having trouble figuring out how to write an init.py file that would allow me to distribute them as a single add-on.  I've posted everything on Github.  The three files aren't too long:   I've read a few other threads, but nothing seems to work for me.  How can I get my init.py to register my operators properly?
65547
See also      Not a major issue, just annoying as I don't want my class to ever be instantiated without the particular arguments.  #include &lt;map&gt;  struct MyClass {     MyClass(int t); };  int main() {     std::map&lt;int, MyClass&gt; myMap;     myMap[14] = MyClass(42); }   This gives me the following g++ error:     /usr/include/c++/4.3/bits/stl_map.h:419: error: no matching function for call to ‘MyClass()’   This compiles fine if I add a default constructor; I am certain it's not caused by incorrect syntax.
5798
Is there any meaningful distinction between:  class A(object):     foo = 5   # some default value   vs.  class B(object):     def __init__(self, foo=5):         self.foo = foo   If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?
54214
An error has occured while executing Python code:  Traceback (most recent call last):   File "/usr/share/qgis/python/pyplugin_installer/installer_data.py", line 460, in xmlDownloaded     if isCompatible(QGis.QGIS_VERSION, qgisMinimumVersion, qgisMaximumVersion):   File "/usr/share/qgis/python/pyplugin_installer/version_compare.py", line 188, in isCompatible     if len(maxVer)TypeError: object of type 'NoneType' has no len()  Python version: 2.7.6 (default, Mar 22 2014, 23:03:41)  [GCC 4.8.2]  When trying to open the plugin manages on Qgis 2.6.1 I get the following error:  QGIS version: 2.6.1-Brighton Brighton, exported  Python path: ['/usr/share/qgis/python/plugins/processing', '/usr/share/qgis/python', u'/home/joseph/.qgis2/python', u'/home/joseph/.qgis2/python/plugins', '/usr/share/qgis/python/plugins', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/share/qgis/python/plugins/fTools/tools']