title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How to get instance variables in Python?
109,087
66
2008-09-20T19:30:24Z
109,106
78
2008-09-20T19:34:17Z
[ "python", "methods", "instance-variables" ]
Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code: ``` class hi: def __init__(self): self.ii = "foo" self.kk = "bar" ``` Is there a way for me to do this: ``` >>> mystery_method(hi) ["ii", "kk"] ``` Thanks guys! Edit: I originally had asked for class variables erroneously. Thanks to all who brought this to my attention!
Every object has a `__dict__` variable containing all the variables and its values in it. Try this ``` >>> hi_obj = hi() >>> hi_obj.__dict__.keys() ```
How to get instance variables in Python?
109,087
66
2008-09-20T19:30:24Z
109,118
13
2008-09-20T19:38:01Z
[ "python", "methods", "instance-variables" ]
Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code: ``` class hi: def __init__(self): self.ii = "foo" self.kk = "bar" ``` Is there a way for me to do this: ``` >>> mystery_method(hi) ["ii", "kk"] ``` Thanks guys! Edit: I originally had asked for class variables erroneously. Thanks to all who brought this to my attention!
You normally can't get instance attributes given just a class, at least not without instantiating the class. You can get instance attributes given an instance, though, or class attributes given a class. See the 'inspect' module. You can't get a list of instance attributes because instances really can have anything as attribute, and -- as in your example -- the normal way to create them is to just assign to them in the \_\_init\_\_ method. An exception is if your class uses slots, which is a fixed list of attributes that the class allows instances to have. Slots are explained in <http://www.python.org/2.2.3/descrintro.html>, but there are various pitfalls with slots; they affect memory layout, so multiple inheritance may be problematic, and inheritance in general has to take slots into account, too.
How to get instance variables in Python?
109,087
66
2008-09-20T19:30:24Z
109,122
8
2008-09-20T19:39:31Z
[ "python", "methods", "instance-variables" ]
Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code: ``` class hi: def __init__(self): self.ii = "foo" self.kk = "bar" ``` Is there a way for me to do this: ``` >>> mystery_method(hi) ["ii", "kk"] ``` Thanks guys! Edit: I originally had asked for class variables erroneously. Thanks to all who brought this to my attention!
You can also test if an object has a specific variable with: ``` >>> hi_obj = hi() >>> hasattr(hi_obj, "some attribute") ```
How to get instance variables in Python?
109,087
66
2008-09-20T19:30:24Z
109,173
63
2008-09-20T20:02:26Z
[ "python", "methods", "instance-variables" ]
Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code: ``` class hi: def __init__(self): self.ii = "foo" self.kk = "bar" ``` Is there a way for me to do this: ``` >>> mystery_method(hi) ["ii", "kk"] ``` Thanks guys! Edit: I originally had asked for class variables erroneously. Thanks to all who brought this to my attention!
Use vars() ``` class Foo(object): def __init__(self): self.a = 1 self.b = 2 vars(Foo()) #==> {'a': 1, 'b': 2} vars(Foo()).keys() #==> ['a', 'b'] ```
How to get instance variables in Python?
109,087
66
2008-09-20T19:30:24Z
4,522,706
10
2010-12-23T21:50:34Z
[ "python", "methods", "instance-variables" ]
Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code: ``` class hi: def __init__(self): self.ii = "foo" self.kk = "bar" ``` Is there a way for me to do this: ``` >>> mystery_method(hi) ["ii", "kk"] ``` Thanks guys! Edit: I originally had asked for class variables erroneously. Thanks to all who brought this to my attention!
Both the Vars() and dict methods will work for the example the OP posted, but they won't work for "loosely" defined objects like: ``` class foo: a = 'foo' b = 'bar' ``` To print all non-callable attributes, you can use the following function: ``` def printVars(object): for i in [v for v in dir(object) if not callable(getattr(object,v))]: print '\n%s:' % i exec('print object.%s\n\n') % i ```
Change the width of form elements created with ModelForm in Django
110,378
42
2008-09-21T06:15:13Z
110,414
91
2008-09-21T06:44:02Z
[ "python", "html", "django", "django-forms", "django-templates" ]
How can i change the width of a textarea form element if i used ModelForm to create it? Here is my product class: ``` class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product ``` And the template code... ``` {% for f in form %} {{ f.name }}:{{ f }} {% endfor %} ``` `f` is the actual form element...
**The easiest way for your use case is to use CSS**. It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS. Example for `long_desc` field in your ProductForm (when your form does not have a custom prefix): ``` #id_long_desc { width: 300px; height: 200px; } ``` **Second approach** is to pass the `attrs` keyword to your widget constructor. ``` class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 20})) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product ``` It's [described in Django documentation](http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs). **Third approach** is to leave the nice declarative interface of newforms for a while and set your widget attributes in custom constructor. ``` class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product # Edit by bryan def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor self.fields['long_desc'].widget.attrs['cols'] = 10 self.fields['long_desc'].widget.attrs['rows'] = 20 ``` This approach has the following advantages: * You can define widget attributes for fields that are generated automatically from your model without redefining whole fields. * It doesn't depend on the prefix of your form.
Change the width of form elements created with ModelForm in Django
110,378
42
2008-09-21T06:15:13Z
640,680
14
2009-03-12T22:02:52Z
[ "python", "html", "django", "django-forms", "django-templates" ]
How can i change the width of a textarea form element if i used ModelForm to create it? Here is my product class: ``` class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product ``` And the template code... ``` {% for f in form %} {{ f.name }}:{{ f }} {% endfor %} ``` `f` is the actual form element...
Excellent answer by zuber, but I believe there's an error in the example code for the third approach. The constructor should be: ``` def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor self.fields['long_desc'].widget.attrs['cols'] = 10 self.fields['long_desc'].widget.attrs['cols'] = 20 ``` The Field objects have no 'attrs' attributes, but their widgets do.
Is there an easy way to request a URL in python and NOT follow redirects?
110,498
24
2008-09-21T07:49:10Z
110,547
34
2008-09-21T08:33:12Z
[ "python", "http", "redirect" ]
Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build\_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.
[Dive Into Python](http://www.diveintopython.net/http_web_services/redirects.html) has a good chapter on handling redirects with urllib2. Another solution is [httplib](http://docs.python.org/library/httplib.html). ``` >>> import httplib >>> conn = httplib.HTTPConnection("www.bogosoft.com") >>> conn.request("GET", "") >>> r1 = conn.getresponse() >>> print r1.status, r1.reason 301 Moved Permanently >>> print r1.getheader('Location') http://www.bogosoft.com/new/location ```
Is there an easy way to request a URL in python and NOT follow redirects?
110,498
24
2008-09-21T07:49:10Z
111,066
8
2008-09-21T13:51:30Z
[ "python", "http", "redirect" ]
Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build\_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.
i suppose this would help ``` from httplib2 import Http def get_html(uri,num_redirections=0): # put it as 0 for not to follow redirects conn = Http() return conn.request(uri,redirections=num_redirections) ```
Is there an easy way to request a URL in python and NOT follow redirects?
110,498
24
2008-09-21T07:49:10Z
5,352,695
10
2011-03-18T13:33:06Z
[ "python", "http", "redirect" ]
Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build\_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.
This is a urllib2 handler that will not follow redirects: ``` class NoRedirectHandler(urllib2.HTTPRedirectHandler): def http_error_302(self, req, fp, code, msg, headers): infourl = urllib.addinfourl(fp, headers, req.get_full_url()) infourl.status = code infourl.code = code return infourl http_error_300 = http_error_302 http_error_301 = http_error_302 http_error_303 = http_error_302 http_error_307 = http_error_302 opener = urllib2.build_opener(NoRedirectHandler()) urllib2.install_opener(opener) ```
Is there an easy way to request a URL in python and NOT follow redirects?
110,498
24
2008-09-21T07:49:10Z
14,678,220
36
2013-02-03T22:42:27Z
[ "python", "http", "redirect" ]
Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build\_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.
Here is the [Requests](http://docs.python-requests.org/en/latest/) way: ``` import requests r = requests.get('http://github.com', allow_redirects=False) print(r.status_code) ```
Dirty fields in django
110,803
26
2008-09-21T11:27:24Z
111,091
11
2008-09-21T14:04:00Z
[ "python", "django" ]
In my app i need to save changed values (old and new) when model gets saved. Any examples or working code? I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.
You haven't said very much about your specific use case or needs. In particular, it would be helpful to know what you need to do with the change information (how long do you need to store it?). If you only need to store it for transient purposes, @S.Lott's session solution may be best. If you want a full audit trail of all changes to your objects stored in the DB, try this [AuditTrail solution](http://code.djangoproject.com/wiki/AuditTrail). **UPDATE**: The AuditTrail code I linked to above is the closest I've seen to a full solution that would work for your case, though it has some limitations (doesn't work at all for ManyToMany fields). It will store all previous versions of your objects in the DB, so the admin could roll back to any previous version. You'd have to work with it a bit if you want the change to not take effect until approved. You could also build a custom solution based on something like @Armin Ronacher's DiffingMixin. You'd store the diff dictionary (maybe pickled?) in a table for the admin to review later and apply if desired (you'd need to write the code to take the diff dictionary and apply it to an instance).
Dirty fields in django
110,803
26
2008-09-21T11:27:24Z
111,364
10
2008-09-21T16:33:51Z
[ "python", "django" ]
In my app i need to save changed values (old and new) when model gets saved. Any examples or working code? I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.
Django is currently sending all columns to the database, even if you just changed one. To change this, some changes in the database system would be necessary. This could be easily implemented on the existing code by adding a set of dirty fields to the model and adding column names to it, each time you `__set__` a column value. If you need that feature, I would suggest you look at the Django ORM, implement it and put a patch into the Django trac. It should be very easy to add that and it would help other users too. When you do that, add a hook that is called each time a column is set. If you don't want to hack on Django itself, you could copy the dict on object creation and diff it. Maybe with a mixin like this: ``` class DiffingMixin(object): def __init__(self, *args, **kwargs): super(DiffingMixin, self).__init__(*args, **kwargs) self._original_state = dict(self.__dict__) def get_changed_columns(self): missing = object() result = {} for key, value in self._original_state.iteritems(): if key != self.__dict__.get(key, missing): result[key] = value return result class MyModel(DiffingMixin, models.Model): pass ``` This code is untested but should work. When you call `model.get_changed_columns()` you get a dict of all changed values. This of course won't work for mutable objects in columns because the original state is a flat copy of the dict.
Dirty fields in django
110,803
26
2008-09-21T11:27:24Z
332,225
18
2008-12-01T21:09:14Z
[ "python", "django" ]
In my app i need to save changed values (old and new) when model gets saved. Any examples or working code? I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.
I've found Armin's idea very useful. Here is my variation; ``` class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) self._original_state = self._as_dict() def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) ``` Edit: I've tested this BTW. Sorry about the long lines. The difference is (aside from the names) it only caches local non-relation fields. In other words it doesn't cache a parent model's fields if present. And there's one more thing; you need to reset \_original\_state dict after saving. But I didn't want to overwrite save() method since most of the times we discard model instances after saving. ``` def save(self, *args, **kwargs): super(Klass, self).save(*args, **kwargs) self._original_state = self._as_dict() ```
Close a tkinter window?
110,923
32
2008-09-21T12:40:04Z
110,929
32
2008-09-21T12:44:01Z
[ "python", "tkinter" ]
How do I end a Tkinter program? Let's say I have this code: ``` from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() ``` How should I define the `quit` function?
We can use: ``` def quit(): root.quit() ``` or ``` def quit(): root.destroy() ```
Close a tkinter window?
110,923
32
2008-09-21T12:40:04Z
294,199
11
2008-11-16T18:36:55Z
[ "python", "tkinter" ]
How do I end a Tkinter program? Let's say I have this code: ``` from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() ``` How should I define the `quit` function?
``` import Tkinter as tk def quit(root): root.destroy() root = tk.Tk() tk.Button(root, text="Quit", command=lambda root=root:quit(root)).pack() root.mainloop() ```
Close a tkinter window?
110,923
32
2008-09-21T12:40:04Z
15,577,605
25
2013-03-22T18:39:54Z
[ "python", "tkinter" ]
How do I end a Tkinter program? Let's say I have this code: ``` from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() ``` How should I define the `quit` function?
``` root.quit() ``` Above line just **Bypasses** the `root.mainloop()` i.e root.mainloop() will still be running in background if quit() command is executed. ``` root.destroy() ``` While destroy() command vanish out `root.mainloop()` i.e root.mainloop() stops. So as you just want to quit the program so you should use `root.destroy()` as it will it stop the mainloop(). But if you want to run some infinite loop and you don't want to destroy your Tk window and want to execute some code after `root.mainloop()` line then you should use `root.quit()`. Ex: ``` from Tkinter import * def quit(): global root root.quit() root = Tk() while True: Button(root, text="Quit", command=quit).pack() root.mainloop() #do something ```
How do I handle the window close event in Tkinter?
111,155
43
2008-09-21T14:46:20Z
111,160
51
2008-09-21T14:51:11Z
[ "python", "events", "tkinter", "window" ]
How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?
Tkinter supports a mechanism called [*protocol handlers*](http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm#protocols). Here, the term *protocol* refers to the interaction between the application and the window manager. The most commonly used protocol is called `WM_DELETE_WINDOW`, and is used to define what happens when the user explicitly closes a window using the window manager. You can use the `protocol` method to *install a handler* for this protocol (the widget must be a `Tk` or `Toplevel` widget): Here you have a concrete example: ``` import tkinter as tk from tkinter import messagebox root = tk.Tk() def on_closing(): if messagebox.askokcancel("Quit", "Do you want to quit?"): root.destroy() root.protocol("WM_DELETE_WINDOW", on_closing) root.mainloop() ```
How do I handle the window close event in Tkinter?
111,155
43
2008-09-21T14:46:20Z
14,819,661
7
2013-02-11T19:46:39Z
[ "python", "events", "tkinter", "window" ]
How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?
Matt has shown one classic modification of the close button. The other is to have the close button minimize the window. You can reproduced this behavior by having the [*iconify*](http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.iconify-method) method be the [*protocol*](http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.protocol-method) method's second argument. Here's a working example, tested on Windows 7: ``` # Python 3 import tkinter import tkinter.scrolledtext as scrolledtext class GUI(object): def __init__(self): root = self.root = tkinter.Tk() root.title('Test') # make the top right close button minimize (iconify) the main window root.protocol("WM_DELETE_WINDOW", root.iconify) # make Esc exit the program root.bind('<Escape>', lambda e: root.destroy()) # create a menu bar with an Exit command menubar = tkinter.Menu(root) filemenu = tkinter.Menu(menubar, tearoff=0) filemenu.add_command(label="Exit", command=root.destroy) menubar.add_cascade(label="File", menu=filemenu) root.config(menu=menubar) # create a Text widget with a Scrollbar attached txt = scrolledtext.ScrolledText(root, undo=True) txt['font'] = ('consolas', '12') txt.pack(expand=True, fill='both') gui = GUI() gui.root.mainloop() ``` In this example we give the user two new exit options: the classic file menu -> Exit, and also the `Esc` button.
What is a "callable" in Python?
111,234
170
2008-09-21T15:34:32Z
111,251
8
2008-09-21T15:43:15Z
[ "python", "callable" ]
Now that it's clear [what a metaclass is](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), 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 ?
A Callable is an object that has the `__call__` method. This means you can fake callable functions or do neat things like [Partial Function Application](http://www.python.org/dev/peps/pep-0309/) where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as [Currying](http://en.wikipedia.org/wiki/Currying) in functional programming circles). Certain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string. This can produce errors where the interpreter attempts to execute a non-callable application. You can see this happening in a python interpreter by doing something like the transcript below. ``` [nigel@k9 ~]$ python Python 2.5 (r25:51908, Nov 6 2007, 15:55:44) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 'aaa'() # <== Here we attempt to call a string. Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object is not callable >>> ```
What is a "callable" in Python?
111,234
170
2008-09-21T15:34:32Z
111,255
181
2008-09-21T15:44:22Z
[ "python", "callable" ]
Now that it's clear [what a metaclass is](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), 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 ?
A callable is anything that can be called. The [built-in *callable* (PyCallable\_Check in objects.c)](http://svn.python.org/projects/python/trunk/Objects/object.c) checks if the argument is either: * an instance of a class with a *\_\_call\_\_* method or * is of a type that has a non null *tp\_call* (c struct) member which indicates callability otherwise (such as in functions, methods etc.) The method named *\_\_call\_\_* is ([according to the documentation](http://docs.python.org/ref/callable-types.html)) > Called when the instance is ''called'' as a function ## Example ``` class Foo: def __call__(self): print 'called' foo_instance = Foo() foo_instance() #this is calling the __call__ method ```
What is a "callable" in Python?
111,234
170
2008-09-21T15:34:32Z
115,349
59
2008-09-22T15:04:53Z
[ "python", "callable" ]
Now that it's clear [what a metaclass is](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), 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 ?
From Python's sources [object.c](http://svn.python.org/view/python/trunk/Objects/object.c?rev=64962&view=markup): ``` /* Test whether an object can be called */ int PyCallable_Check(PyObject *x) { if (x == NULL) return 0; if (PyInstance_Check(x)) { PyObject *call = PyObject_GetAttrString(x, "__call__"); if (call == NULL) { PyErr_Clear(); return 0; } /* Could test recursively but don't, for fear of endless recursion if some joker sets self.__call__ = self */ Py_DECREF(call); return 1; } else { return x->ob_type->tp_call != NULL; } } ``` It says: 1. If an object is an instance of some class then it is callable *iff* it has `__call__` attribute. 2. Else the object `x` is callable *iff* `x->ob_type->tp_call != NULL` Desciption of [`tp_call` field](http://docs.python.org/api/type-structs.html): > `ternaryfunc tp_call` An optional > pointer to a function that implements > calling the object. This should be > NULL if the object is not callable. > The signature is the same as for > PyObject\_Call(). This field is > inherited by subtypes. You can always use built-in `callable` function to determine whether given object is callable or not; or better yet just call it and catch `TypeError` later. `callable` is removed in Python 3.0 and 3.1, use `callable = lambda o: hasattr(o, '__call__')` or `isinstance(o, collections.Callable)`. Example, a simplistic cache implementation: ``` class Cached: def __init__(self, function): self.function = function self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: ret = self.cache[args] = self.function(*args) return ret ``` Usage: ``` @Cached def ack(x, y): return ack(x-1, ack(x, y-1)) if x*y else (x + y + 1) ``` Example from standard library, file [`site.py`](http://svn.python.org/projects/python/trunk/Lib/site.py), definition of built-in `exit()` and `quit()` functions: ``` class Quitter(object): def __init__(self, name): self.name = name def __repr__(self): return 'Use %s() or %s to exit' % (self.name, eof) def __call__(self, code=None): # Shells like IDLE catch the SystemExit, but listen when their # stdin wrapper is closed. try: sys.stdin.close() except: pass raise SystemExit(code) __builtin__.quit = Quitter('quit') __builtin__.exit = Quitter('exit') ```
What is a "callable" in Python?
111,234
170
2008-09-21T15:34:32Z
139,469
19
2008-09-26T13:22:20Z
[ "python", "callable" ]
Now that it's clear [what a metaclass is](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), 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 ?
A callable is an object allows you to use round parenthesis ( ) and eventually pass some parameters, just like functions. Every time you define a function python creates a callable object. In example, you could define the function **func** in these ways (it's the same): ``` class a(object): def __call__(self, *args): print 'Hello' func = a() # or ... def func(*args): print 'Hello' ``` You could use this method instead of methods like **doit** or **run**, I think it's just more clear to see obj() than obj.doit()
What is a "callable" in Python?
111,234
170
2008-09-21T15:34:32Z
15,581,536
12
2013-03-22T23:38:33Z
[ "python", "callable" ]
Now that it's clear [what a metaclass is](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), 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 ?
Let me explain backwards: Consider this... ``` foo() ``` ... as syntactic sugar for: ``` foo.__call__() ``` Where `foo` can be any object that responds to `__call__`. When I say any object, I mean it: built-in types, your own classes and their instances. In the case of built-in types, when you write: ``` int('10') unicode(10) ``` You're essentially doing: ``` int.__call__('10') unicode.__call__(10) ``` That's also why you don't have `foo = new int` in Python: you just make the class object return an instance of it on `__call__`. The way Python solves this is very elegant in my opinion.
How do I find out the size of a canvas item in Python/Tkinter?
111,934
3
2008-09-21T20:08:56Z
111,974
11
2008-09-21T20:19:34Z
[ "python", "tkinter", "tkinter-canvas" ]
I want to create some text in a canvas: ``` myText = self.canvas.create_text(5, 5, anchor=NW, text="TEST") ``` Now how do I find the width and height of myText?
``` bounds = self.canvas.bbox(myText) # returns a tuple like (x1, y1, x2, y2) width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] ``` See the [TkInter reference](http://infohost.nmt.edu/tcc/help/pubs/tkinter/canvas-methods.html).
Is there any way to do HTTP PUT in python
111,945
166
2008-09-21T20:11:05Z
111,973
8
2008-09-21T20:18:57Z
[ "python", "http", "put" ]
I need to upload some data to a server using HTTP `PUT` in python. From my brief reading of the urllib2 docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in python?
You should have a look at the [httplib module](http://docs.python.org/lib/module-httplib.html). It should let you make whatever sort of HTTP request you want.
Is there any way to do HTTP PUT in python
111,945
166
2008-09-21T20:11:05Z
111,988
197
2008-09-21T20:24:21Z
[ "python", "http", "put" ]
I need to upload some data to a server using HTTP `PUT` in python. From my brief reading of the urllib2 docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in python?
``` import urllib2 opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request('http://example.org', data='your_put_data') request.add_header('Content-Type', 'your/contenttype') request.get_method = lambda: 'PUT' url = opener.open(request) ```
Is there any way to do HTTP PUT in python
111,945
166
2008-09-21T20:11:05Z
114,648
8
2008-09-22T12:46:40Z
[ "python", "http", "put" ]
I need to upload some data to a server using HTTP `PUT` in python. From my brief reading of the urllib2 docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in python?
I needed to solve this problem too a while back so that I could act as a client for a RESTful API. I settled on httplib2 because it allowed me to send PUT and DELETE in addition to GET and POST. Httplib2 is not part of the standard library but you can easily get it from the cheese shop.
Is there any way to do HTTP PUT in python
111,945
166
2008-09-21T20:11:05Z
3,919,484
45
2010-10-12T22:13:42Z
[ "python", "http", "put" ]
I need to upload some data to a server using HTTP `PUT` in python. From my brief reading of the urllib2 docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in python?
Httplib seems like a cleaner choice. ``` import httplib connection = httplib.HTTPConnection('1.2.3.4:1234') body_content = 'BODY CONTENT GOES HERE' connection.request('PUT', '/url/path/to/put/to', body_content) result = connection.getresponse() # Now result.status and result.reason contains interesting stuff ```
Is there any way to do HTTP PUT in python
111,945
166
2008-09-21T20:11:05Z
8,259,648
231
2011-11-24T15:54:13Z
[ "python", "http", "put" ]
I need to upload some data to a server using HTTP `PUT` in python. From my brief reading of the urllib2 docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in python?
I've used a variety of python HTTP libs in the past, and I've settled on '[Requests](http://docs.python-requests.org/en/latest/index.html)' as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like: ``` payload = {'username': 'bob', 'email': '[email protected]'} >>> r = requests.put("http://somedomain.org/endpoint", data=payload) ``` You can then check the response status code with: ``` r.status_code ``` or the response with: ``` r.content ``` Requests has a lot synactic sugar and shortcuts that'll make your life easier.
Using Python's ftplib to get a directory listing, portably
111,954
35
2008-09-21T20:13:18Z
111,966
73
2008-09-21T20:15:59Z
[ "python", "ftp", "portability" ]
You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is: ``` # File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line ``` Which yields: ``` $ python ftplib-example-1.py - total 34 - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 . - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .. - drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS - lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -> welcome.msg - drwxr-xr-x 3 root wheel 512 May 19 1998 bin - drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev - drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup - drwxr-xr-x 3 root wheel 512 May 19 1998 etc ... ``` I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list. Is there a portable way to get an array filled with the directory listing? (The array should only have the folder names.)
Try to use `ftp.nlst(dir)`. However, note that if the folder is empty, it might throw an error: ``` files = [] try: files = ftp.nlst() except ftplib.error_perm, resp: if str(resp) == "550 No files found": print "No files in this directory" else: raise for f in files: print f ```
Using Python's ftplib to get a directory listing, portably
111,954
35
2008-09-21T20:13:18Z
8,474,838
20
2011-12-12T13:10:19Z
[ "python", "ftp", "portability" ]
You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is: ``` # File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line ``` Which yields: ``` $ python ftplib-example-1.py - total 34 - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 . - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .. - drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS - lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -> welcome.msg - drwxr-xr-x 3 root wheel 512 May 19 1998 bin - drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev - drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup - drwxr-xr-x 3 root wheel 512 May 19 1998 etc ... ``` I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list. Is there a portable way to get an array filled with the directory listing? (The array should only have the folder names.)
The reliable/standardized way to parse FTP directory listing is by using MLSD command, which by now should be supported by all recent/decent FTP servers. ``` import ftplib f = ftplib.FTP() f.connect("localhost") f.login() ls = [] f.retrlines('MLSD', ls.append) for entry in ls: print entry ``` The code above will print: ``` modify=20110723201710;perm=el;size=4096;type=dir;unique=807g4e5a5; tests modify=20111206092323;perm=el;size=4096;type=dir;unique=807g1008e0; .xchat2 modify=20111022125631;perm=el;size=4096;type=dir;unique=807g10001a; .gconfd modify=20110808185618;perm=el;size=4096;type=dir;unique=807g160f9a; .skychart ... ``` Starting from python 3.3, ftplib will provide a specific method to do this: * <http://bugs.python.org/issue11072> * <http://hg.python.org/cpython/file/67053b135ed9/Lib/ftplib.py#l535>
python.array versus numpy.array
111,983
27
2008-09-21T20:23:02Z
112,025
40
2008-09-21T20:31:39Z
[ "python", "numpy" ]
If you are creating a 1d array in Python is there any benefit to using the NumPy package?
It all depends on what you plan to do with the array. If all you're doing is creating arrays of simple data types and doing I/O, the [array](http://docs.python.org/lib/module-array.html) module will do just fine. If, on the other hand, you want to do any kind of numerical calculations, the array module doesn't provide any help with that. [NumPy](http://numpy.scipy.org/array_interface.shtml) (and [SciPy](http://scipy.org)) give you a wide variety of operations between arrays and special functions that are useful not only for scientific work but for things like advanced image manipulation or in general anything where you need to perform efficient calculations with large amounts of data. Numpy is also much more flexible, e.g. it supports arrays of any type of Python objects, and is also able to interact "natively" with your own objects if they conform to the [array interface](http://numpy.scipy.org/).
List all words in a dictionary that start with <user input>
112,532
7
2008-09-21T23:28:06Z
112,557
8
2008-09-21T23:35:09Z
[ "python", "list", "dictionary" ]
How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! --- Edit: I'm using python, but I assume that this is a fairly language-independent problem.
One of the best ways to do this is to use a directed graph to store your dictionary. It takes a little bit of setting up, but once done it is fairly easy to then do the type of searches you are talking about. The nodes in the graph correspond to a letter in your word, so each node will have one incoming link and up to 26 (in English) outgoing links. You could also use a hybrid approach where you maintain a sorted list containing your dictionary and use the directed graph as an index into your dictionary. Then you just look up your prefix in your directed graph and then go to that point in your dictionary and spit out all words matching your search criteria.
List all words in a dictionary that start with <user input>
112,532
7
2008-09-21T23:28:06Z
112,559
10
2008-09-21T23:35:48Z
[ "python", "list", "dictionary" ]
How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! --- Edit: I'm using python, but I assume that this is a fairly language-independent problem.
Use a [trie](http://en.wikipedia.org/wiki/Trie). Add your list of words to a trie. Each path from the root to a leaf is a valid word. A path from a root to an intermediate node represents a prefix, and the children of the intermediate node are valid completions for the prefix.
py2exe - generate single executable file
112,698
112
2008-09-22T00:49:12Z
112,713
72
2008-09-22T00:55:46Z
[ "python", "packaging", "py2exe" ]
I thought I heard that [py2exe](http://www.py2exe.org/) was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used? Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.
[PyInstaller](http://www.pyinstaller.org/) will create a single .exe file with no dependencies; use the `--onefile` option. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see [minty's answer](http://stackoverflow.com/questions/112698/py2exe-generate-single-executable-file#113014)) I use the version of PyInstaller from svn, since the latest release (1.3) is somewhat outdated. It's been working really well for an app which depends on PyQt, PyQwt, numpy, scipy and a few more.
py2exe - generate single executable file
112,698
112
2008-09-22T00:49:12Z
113,014
150
2008-09-22T03:19:08Z
[ "python", "packaging", "py2exe" ]
I thought I heard that [py2exe](http://www.py2exe.org/) was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used? Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.
The way to do this using py2exe is to use the bundle\_files option in your setup.py file. For a single file you will want to set `bundle_files` to 1, `compressed` to True, and set the zipfile option to None. That way it creates one compressed file for easy distribution. Here is a more complete description of the bundle\_file option quoted directly from the [py2exe site](http://www.py2exe.org/index.cgi/SingleFileExecutable?highlight=%28file%29|%28single%29)\* > Using "bundle\_files" and "zipfile" > > An easier (and better) way to create > single-file executables is to set > bundle\_files to 1 or 2, and to set > zipfile to None. This approach does > not require extracting files to a > temporary location, which provides > much faster program startup. > > Valid values for bundle\_files are: > > * 3 (default) don't bundle > * 2 bundle everything but the Python interpreter > * 1 bundle everything, including the Python interpreter > > If zipfile is set to None, the files will be bundle > within the executable instead of library.zip. Here is a sample setup.py: ``` from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 1, 'compressed': True}}, windows = [{'script': "single.py"}], zipfile = None, ) ```
py2exe - generate single executable file
112,698
112
2008-09-22T00:49:12Z
333,483
8
2008-12-02T09:44:45Z
[ "python", "packaging", "py2exe" ]
I thought I heard that [py2exe](http://www.py2exe.org/) was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used? Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.
As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program. Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program. I have used InnoSetup ( <http://www.jrsoftware.org/isinfo.php> ) with delight for several years and for commercial programs, so I heartily recommend it.
Python - When to use file vs open
112,970
119
2008-09-22T03:04:14Z
112,980
129
2008-09-22T03:07:44Z
[ "python", "file" ]
What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)
You should always use `open()`. As the [documentation](http://docs.python.org/2/library/functions.html#file "BuiltinFuncs Doc") states: > When opening a file, it's preferable > to use open() instead of invoking this > constructor directly. file is more > suited to type testing (for example, > writing "isinstance(f, file)"). Also, `file()` [has been removed](http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins) since Python 3.0.
Python - When to use file vs open
112,970
119
2008-09-22T03:04:14Z
112,989
28
2008-09-22T03:10:16Z
[ "python", "file" ]
What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)
Two reasons: The python philosophy of "There ought to be one way to do it" and `file` is going away. `file` is the actual type (using e.g. `file('myfile.txt')` is calling its constructor). `open` is a factory function that will return a file object. In python 3.0 `file` is going to move from being a built-in to being implemented by multiple classes in the `io` library (somewhat similar to Java with buffered readers, etc.)
Python - When to use file vs open
112,970
119
2008-09-22T03:04:14Z
113,050
16
2008-09-22T03:32:08Z
[ "python", "file" ]
What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)
`file()` is a type, like an int or a list. `open()` is a function for opening files, and will return a `file` object. This is an example of when you should use open: ``` f = open(filename, 'r') for line in f: process(line) f.close() ``` This is an example of when you should use file: ``` class LoggingFile(file): def write(self, data): sys.stderr.write("Wrote %d bytes\n" % len(data)) super(LoggingFile, self).write(data) ``` As you can see, there's a good reason for both to exist, and a clear use-case for both.
Writing to the windows logs in Python
113,007
9
2008-09-22T03:15:31Z
113,011
12
2008-09-22T03:16:58Z
[ "python", "windows", "logging" ]
Is it possible to write to the windows logs in python?
Yes, just use Windows Python Extension, as stated [here](http://www.ravenbrook.com/project/p4dti/master/design/win32-eventlog/). ``` import win32evtlogutil win32evtlogutil.ReportEvent(ApplicationName, EventID, EventCategory, EventType, Inserts, Data, SID) ```
Is there a function in Python to split a string without ignoring the spaces?
113,534
12
2008-09-22T07:02:04Z
113,555
40
2008-09-22T07:08:04Z
[ "python", "split" ]
Is there a function in Python to split a string without ignoring the spaces in the resulting list? E.g: ``` s="This is the string I want to split".split() ``` gives me ``` >>> s ['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split'] ``` I want something like ``` ['This',' ','is',' ', 'the',' ','string', ' ', .....] ```
``` >>> import re >>> re.split(r"(\s+)", "This is the string I want to split") ['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split'] ``` Using the capturing parentheses in re.split() causes the function to return the separators as well.
Is there a function in python to split a word into a list?
113,655
41
2008-09-22T07:40:50Z
113,662
119
2008-09-22T07:42:15Z
[ "python", "function", "split" ]
Is there a function in python to split a word into a list of single letters? e.g: ``` s="Word to Split" ``` to get ``` wordlist=['W','o','r','d','','t','o' ....] ```
``` >>> list("Word to Split") ['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't'] ```
Is there a function in python to split a word into a list?
113,655
41
2008-09-22T07:40:50Z
113,680
9
2008-09-22T07:46:45Z
[ "python", "function", "split" ]
Is there a function in python to split a word into a list of single letters? e.g: ``` s="Word to Split" ``` to get ``` wordlist=['W','o','r','d','','t','o' ....] ```
The easiest way is probably just to use `list()`, but there is at least one other option as well: ``` s = "Word to Split" wordlist = list(s) # option 1, wordlist = [ch for ch in s] # option 2, list comprehension. ``` They should *both* give you what you need: ``` ['W','o','r','d',' ','t','o',' ','S','p','l','i','t'] ``` As stated, the first is likely the most preferable for your example but there are use cases that may make the latter quite handy for more complex stuff, such as if you want to apply some arbitrary function to the items, such as with: ``` [doSomethingWith(ch) for ch in s] ```
Deploying Django: How do you do it?
114,112
12
2008-09-22T10:11:48Z
114,268
7
2008-09-22T11:06:01Z
[ "python", "django-deployment" ]
I have tried following guides like [this one](http://docs.djangoproject.com/en/dev/howto/deployment/modpython/) but it just didnt work for me. **So my question is this:** What is a good guide for deploying Django, and how do you deploy your Django. I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what it does (apart from automation of deploying code), or even if i want/need to use it or not.
`mod_wsgi` in combination with a `virtualenv` for all the dependencies, a mercurial checkout into the virtualenv and a `fabric` recipe to check out the changes on the server. I wrote an article about my usual workflow: [Deploying Python Web Applications](http://lucumr.pocoo.org/2008/7/17/deploying-python-web-applications/). Hope that helps.
Class method differences in Python: bound, unbound and static
114,214
190
2008-09-22T10:49:43Z
114,232
10
2008-09-22T10:56:27Z
[ "python" ]
What is the difference between the following class methods? Is it that one is static and the other is not? ``` class Test(object): def method_one(self): print "Called method_one" def method_two(): print "Called method_two" a_test = Test() a_test.method_one() a_test.method_two() ```
When you call a class member, Python automatically uses a reference to the object as the first parameter. The variable `self` actually means nothing, it's just a coding convention. You could call it `gargaloo` if you wanted. That said, the call to `method_two` would raise a `TypeError`, because Python is automatically trying to pass a parameter (the reference to its parent object) to a method that was defined as having no parameters. To actually make it work, you could append this to your class definition: ``` method_two = staticmethod(method_two) ``` or you could use the `@staticmethod` [function decorator](https://docs.python.org/2/library/functions.html#staticmethod).
Class method differences in Python: bound, unbound and static
114,214
190
2008-09-22T10:49:43Z
114,267
325
2008-09-22T11:05:54Z
[ "python" ]
What is the difference between the following class methods? Is it that one is static and the other is not? ``` class Test(object): def method_one(self): print "Called method_one" def method_two(): print "Called method_two" a_test = Test() a_test.method_one() a_test.method_two() ```
In Python, there is a distinction between *bound* and *unbound* methods. Basically, a call to a member function (like `method_one`), a bound function ``` a_test.method_one() ``` is translated to ``` Test.method_one(a_test) ``` i.e. a call to an unbound method. Because of that, a call to your version of `method_two` will fail with a `TypeError` ``` >>> a_test = Test() >>> a_test.method_two() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: method_two() takes no arguments (1 given) ``` You can change the behavior of a method using a decorator ``` class Test(object): def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method two" ``` The decorator tells the built-in default metaclass `type` (the class of a class, cf. [this question](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python)) to not create bound methods for `method_two`. Now, you can invoke static method both on an instance or on the class directly: ``` >>> a_test = Test() >>> a_test.method_one() Called method_one >>> a_test.method_two() Called method_two >>> Test.method_two() Called method_two ```
Class method differences in Python: bound, unbound and static
114,214
190
2008-09-22T10:49:43Z
114,289
163
2008-09-22T11:12:36Z
[ "python" ]
What is the difference between the following class methods? Is it that one is static and the other is not? ``` class Test(object): def method_one(self): print "Called method_one" def method_two(): print "Called method_two" a_test = Test() a_test.method_one() a_test.method_two() ```
Methods in Python are a very, very simple thing once you understood the basics of the descriptor system. Imagine the following class: ``` class C(object): def foo(self): pass ``` Now let's have a look at that class in the shell: ``` >>> C.foo <unbound method C.foo> >>> C.__dict__['foo'] <function foo at 0x17d05b0> ``` As you can see if you access the `foo` attribute on the class you get back an unbound method, however inside the class storage (the dict) there is a function. Why's that? The reason for this is that the class of your class implements a `__getattribute__` that resolves descriptors. Sounds complex, but is not. `C.foo` is roughly equivalent to this code in that special case: ``` >>> C.__dict__['foo'].__get__(None, C) <unbound method C.foo> ``` That's because functions have a `__get__` method which makes them descriptors. If you have an instance of a class it's nearly the same, just that `None` is the class instance: ``` >>> c = C() >>> C.__dict__['foo'].__get__(c, C) <bound method C.foo of <__main__.C object at 0x17bd4d0>> ``` Now why does Python do that? Because the method object binds the first parameter of a function to the instance of the class. That's where self comes from. Now sometimes you don't want your class to make a function a method, that's where `staticmethod` comes into play: ``` class C(object): @staticmethod def foo(): pass ``` The `staticmethod` decorator wraps your class and implements a dummy `__get__` that returns the wrapped function as function and not as a method: ``` >>> C.__dict__['foo'].__get__(None, C) <function foo at 0x17d0c30> ``` Hope that explains it.
Class method differences in Python: bound, unbound and static
114,214
190
2008-09-22T10:49:43Z
2,696,019
10
2010-04-23T03:25:12Z
[ "python" ]
What is the difference between the following class methods? Is it that one is static and the other is not? ``` class Test(object): def method_one(self): print "Called method_one" def method_two(): print "Called method_two" a_test = Test() a_test.method_one() a_test.method_two() ```
``` >>> class Class(object): ... def __init__(self): ... self.i = 0 ... def instance_method(self): ... self.i += 1 ... print self.i ... c = 0 ... @classmethod ... def class_method(cls): ... cls.c += 1 ... print cls.c ... @staticmethod ... def static_method(s): ... s += 1 ... print s ... >>> a = Class() >>> a.class_method() 1 >>> Class.class_method() # The class shares this value across instances 2 >>> a.instance_method() 1 >>> Class.instance_method() # The class cannot use an instance method Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method instance_method() must be called with Class instance as first argument (got nothing instead) >>> Class.instance_method(a) 2 >>> b = 0 >>> a.static_method(b) 1 >>> a.static_method(a.c) # Static method does not have direct access to >>> # class or instance properties. 3 >>> Class.c # a.c above was passed by value and not by reference. 2 >>> a.c 2 >>> a.c = 5 # The connection between the instance >>> Class.c # and its class is weak as seen here. 2 >>> Class.class_method() 3 >>> a.c 5 ```
Is a Python dictionary an example of a hash table?
114,830
88
2008-09-22T13:22:28Z
114,831
127
2008-09-22T13:23:00Z
[ "python", "hash", "dictionary", "hashmap", "hashtable" ]
One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?
Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, [here](http://mail.python.org/pipermail/python-list/2000-March/048085.html). That's why you can't use something 'not hashable' as a dict key, like a list: ``` >>> a = {} >>> b = ['some', 'list'] >>> hash(b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list objects are unhashable >>> a[b] = 'some' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list objects are unhashable ``` You can [read more about hash tables](http://en.wikipedia.org/wiki/Hash_table) or [check how it has been implemented in python](https://hg.python.org/cpython/file/10eea15880db/Objects/dictobject.c) and [why it is implemented that way](https://hg.python.org/cpython/file/10eea15880db/Objects/dictnotes.txt).
Is a Python dictionary an example of a hash table?
114,830
88
2008-09-22T13:22:28Z
114,848
14
2008-09-22T13:25:27Z
[ "python", "hash", "dictionary", "hashmap", "hashtable" ]
One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?
Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 ([source](http://mail.python.org/pipermail/python-list/2000-February/023645.html)).
Is a Python dictionary an example of a hash table?
114,830
88
2008-09-22T13:22:28Z
114,853
25
2008-09-22T13:26:19Z
[ "python", "hash", "dictionary", "hashmap", "hashtable" ]
One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?
If you're interested in the technical details, one article in [Beautiful Code](http://oreilly.com/catalog/9780596510046/) deals with the internals of Python's `dict` implementation.
How can I consume a WSDL (SOAP) web service in Python?
115,316
102
2008-09-22T14:58:53Z
115,700
9
2008-09-22T15:55:07Z
[ "python", "web-services", "soap" ]
I want to use a WSDL SOAP based web service in Python. I have looked at the [Dive Into Python](http://diveintopython.net/soap_web_services/) code but the SOAPpy module does not work under Python 2.5. I have tried using [suds](https://fedorahosted.org/suds) which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item'). I have also looked at [Client](http://trac.optio.webfactional.com/wiki) but this does not appear to support WSDL. And I have looked at [ZSI](http://pywebsvcs.sourceforge.net/zsi.html) but it looks very complex. Does anyone have any sample code for it? The WSDL is <https://ws.pingdom.com/soap/PingdomAPI.wsdl> and works fine with the PHP 5 SOAP client.
Right now (as of 2008), all the SOAP libraries available for Python suck. I recommend avoiding SOAP if possible. The last time we where forced to use a SOAP web service from Python, we wrote a wrapper in C# that handled the SOAP on one side and spoke COM out the other.
How can I consume a WSDL (SOAP) web service in Python?
115,316
102
2008-09-22T14:58:53Z
1,793,052
30
2009-11-24T21:32:02Z
[ "python", "web-services", "soap" ]
I want to use a WSDL SOAP based web service in Python. I have looked at the [Dive Into Python](http://diveintopython.net/soap_web_services/) code but the SOAPpy module does not work under Python 2.5. I have tried using [suds](https://fedorahosted.org/suds) which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item'). I have also looked at [Client](http://trac.optio.webfactional.com/wiki) but this does not appear to support WSDL. And I have looked at [ZSI](http://pywebsvcs.sourceforge.net/zsi.html) but it looks very complex. Does anyone have any sample code for it? The WSDL is <https://ws.pingdom.com/soap/PingdomAPI.wsdl> and works fine with the PHP 5 SOAP client.
I know this is an old thread but it was showing up at the top of Google's results so I wanted to share a more current discussion on Python and SOAP. See: <http://www.diveintopython.net/soap_web_services/index.html>
How can I consume a WSDL (SOAP) web service in Python?
115,316
102
2008-09-22T14:58:53Z
2,829,486
44
2010-05-13T19:02:39Z
[ "python", "web-services", "soap" ]
I want to use a WSDL SOAP based web service in Python. I have looked at the [Dive Into Python](http://diveintopython.net/soap_web_services/) code but the SOAPpy module does not work under Python 2.5. I have tried using [suds](https://fedorahosted.org/suds) which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item'). I have also looked at [Client](http://trac.optio.webfactional.com/wiki) but this does not appear to support WSDL. And I have looked at [ZSI](http://pywebsvcs.sourceforge.net/zsi.html) but it looks very complex. Does anyone have any sample code for it? The WSDL is <https://ws.pingdom.com/soap/PingdomAPI.wsdl> and works fine with the PHP 5 SOAP client.
I would recommend that you have a look at [SUDS](https://fedorahosted.org/suds/) "Suds is a lightweight SOAP python client for consuming Web Services."
How can I consume a WSDL (SOAP) web service in Python?
115,316
102
2008-09-22T14:58:53Z
27,302,096
12
2014-12-04T19:13:20Z
[ "python", "web-services", "soap" ]
I want to use a WSDL SOAP based web service in Python. I have looked at the [Dive Into Python](http://diveintopython.net/soap_web_services/) code but the SOAPpy module does not work under Python 2.5. I have tried using [suds](https://fedorahosted.org/suds) which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item'). I have also looked at [Client](http://trac.optio.webfactional.com/wiki) but this does not appear to support WSDL. And I have looked at [ZSI](http://pywebsvcs.sourceforge.net/zsi.html) but it looks very complex. Does anyone have any sample code for it? The WSDL is <https://ws.pingdom.com/soap/PingdomAPI.wsdl> and works fine with the PHP 5 SOAP client.
I recently stumbled up on the same problem. Here is the synopsis of my solution. *(If you need to see the whole discussion, here is the link for complete discussion of the solution: <http://tedbelay.blogspot.com/2014/12/soap-web-service-client-in-python-27.html>)* **Basic constituent code blocks needed** The following are the required basic code blocks of your client application 1. Session request section: request a session with the provider 2. Session authentication section: provide credentials to the provider 3. Client section: create the Client 4. Security Header section: add the WS-Security Header to the Client 5. Consumption section: consume available operations (or methods) as needed **What modules do you need?** Many suggested to use Python modules such as urllib2 ; however, none of the modules work-at least for this particular project. So, here is the list of the modules you need to get. First of all, you need to download and install the latest version of suds from the following link: > pypi.python.org/pypi/suds-jurko/0.4.1.jurko.2 Additionally, you need to download and install requests and suds\_requests modules from the following links respectively ( disclaimer: I am new to post in here, so I can't post more than one link for now). > pypi.python.org/pypi/requests > > pypi.python.org/pypi/suds\_requests/0.1 Once you successfully download and install these modules, you are good to go. **The code** Following the steps outlined earlier, the code looks like the following: Imports: ``` import logging from suds.client import Client from suds.wsse import * from datetime import timedelta,date,datetime,tzinfo import requests from requests.auth import HTTPBasicAuth import suds_requests ``` Session request and authentication: ``` username=input('Username:') password=input('password:') session = requests.session() session.auth=(username, password) ``` Create the Client: ``` client = Client(WSDL_URL, faults=False, cachingpolicy=1, location=WSDL_URL, transport=suds_requests.RequestsTransport(session)) ``` Add WS-Security Header: ``` ... addSecurityHeader(client,username,password) .... def addSecurityHeader(client,username,password): security=Security() userNameToken=UsernameToken(username,password) timeStampToken=Timestamp(validity=600) security.tokens.append(userNameToken) security.tokens.append(timeStampToken) client.set_options(wsse=security) ``` Please note that this method creates the security header depicted in Fig.1. So, your implementation may vary depending on the correct security header format provided by the owner of the service you are consuming. Consume the relevant method (or operation) : ``` result=client.service.methodName(Inputs) ``` **Logging**: One of the best practices in such implementations as this one is logging to see how the communication is executed. In case there is some issue, it makes debugging easy. The following code does basic logging. However, you can log many aspects of the communication in addition to the ones depicted in the code. ``` logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) logging.getLogger('suds.transport').setLevel(logging.DEBUG) ``` **Result:** Here is the result in my case. Note that the server returned HTTP 200. This is the standard success code for HTTP request-response. ``` (200, (collectionNodeLmp){ timestamp = 2014-12-03 00:00:00-05:00 nodeLmp[] = (nodeLmp){ pnodeId = 35010357 name = "YADKIN" mccValue = -0.19 mlcValue = -0.13 price = 36.46 type = "500 KV" timestamp = 2014-12-03 01:00:00-05:00 errorCodeId = 0 }, (nodeLmp){ pnodeId = 33138769 name = "ZION 1" mccValue = -0.18 mlcValue = -1.86 price = 34.75 type = "Aggregate" timestamp = 2014-12-03 01:00:00-05:00 errorCodeId = 0 }, }) ```
Which is more pythonic, factory as a function in a module, or as a method on the class it creates?
115,764
3
2008-09-22T16:03:41Z
115,853
11
2008-09-22T16:20:38Z
[ "python", "factory" ]
I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file. The calendar object just has a method that adds events as they get parsed. Now I want to create a factory function that creates a calendar from a file object, path, or URL. I've been using the [iCalendar python module](http://codespeak.net/icalendar/), which implements a factory function as a class method directly on the Class that it returns an instance of: ``` cal = icalendar.Calendar.from_string(data) ``` From what little I know about Java, this is a common pattern in Java code, though I seem to find more references to a factory method being on a different class than the class you actually want to instantiate instances from. The question is, is this also considered Pythonic ? Or is it considered more pythonic to just create a module-level method as the factory function ?
[**Note**. Be very cautious about separating "Calendar" a collection of events, and "Event" - a single event on a calendar. In your question, it seems like there could be some confusion.] There are many variations on the Factory design pattern. 1. A stand-alone convenience function (e.g., calendarMaker(data)) 2. A separate class (e.g., CalendarParser) which builds your target class (Calendar). 3. A class-level method (e.g. Calendar.from\_string) method. These have different purposes. All are Pythonic, the questions are "what do you *mean*?" and "what's likely to change?" Meaning is everything; change is important. Convenience functions are Pythonic. Languages like Java can't have free-floating functions; you must wrap a lonely function in a class. Python allows you to have a lonely function without the overhead of a class. A function is relevant when your constructor has no state changes or alternate strategies or any memory of previous actions. Sometimes folks will define a class and then provide a convenience function that makes an instance of the class, sets the usual parameters for state and strategy and any other configuration, and then calls the single relevant method of the class. This gives you both the statefulness of class plus the flexibility of a stand-alone function. The class-level method pattern is used, but it has limitations. One, it's forced to rely on class-level variables. Since these can be confusing, a complex constructor as a static method runs into problems when you need to add features (like statefulness or alternative strategies.) Be sure you're never going to expand the static method. Two, it's more-or-less irrelevant to the rest of the class methods and attributes. This kind of `from_string` is just one of many alternative encodings for your Calendar objects. You might have a `from_xml`, `from_JSON`, `from_YAML` and on and on. None of this has the least relevance to what a Calendar IS or what it DOES. These methods are all about how a Calendar is encoded for transmission. What you'll see in the mature Python libraries is that factories are separate from the things they create. Encoding (as strings, XML, JSON, YAML) is subject to a great deal of more-or-less random change. The essential thing, however, rarely changes. Separate the two concerns. Keep encoding and representation as far away from state and behavior as you can.
How do I configure the ip address with CherryPy?
115,773
15
2008-09-22T16:04:54Z
115,826
13
2008-09-22T16:16:12Z
[ "python", "cherrypy" ]
I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 but not through the IP or the windows machine name. It could be a machine configuration difference or a newer version of CherryPy or Python. Any ideas how I can bind to the correct IP address? Edit: to make it clear, I currently don't have a config file at all.
That depends on how you are running the cherrypy init. If using cherrypy 3.1 syntax, that wold do it: ``` cherrypy.server.socket_host = 'www.machinename.com' cherrypy.engine.start() cherrypy.engine.block() ``` Of course you can have something more fancy, like subclassing the server class, or using config files. Those uses are covered in [the documentation](http://www.cherrypy.org/wiki/ServerAPI). But that should be enough. If not just tell us what you are doing and cherrypy version, and I will edit this answer.
How do I configure the ip address with CherryPy?
115,773
15
2008-09-22T16:04:54Z
152,012
29
2008-09-30T06:55:25Z
[ "python", "cherrypy" ]
I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 but not through the IP or the windows machine name. It could be a machine configuration difference or a newer version of CherryPy or Python. Any ideas how I can bind to the correct IP address? Edit: to make it clear, I currently don't have a config file at all.
``` server.socket_host: '0.0.0.0' ``` ...would also work. That's IPv4 INADDR\_ANY, which means, "listen on all interfaces". In a config file, the syntax is: ``` [global] server.socket_host: '0.0.0.0' ``` In code: ``` cherrypy.server.socket_host = '0.0.0.0' ```
Convert mysql timestamp to epoch time in python
115,866
6
2008-09-22T16:22:16Z
115,903
24
2008-09-22T16:26:51Z
[ "python", "mysql", "time", "timestamp" ]
Convert mysql timestamp to epoch time in python - is there an easy way to do this?
Why not let MySQL do the hard work? select unix\_timestamp(fieldname) from tablename;
Convert mysql timestamp to epoch time in python
115,866
6
2008-09-22T16:22:16Z
2,407,400
7
2010-03-09T07:51:59Z
[ "python", "mysql", "time", "timestamp" ]
Convert mysql timestamp to epoch time in python - is there an easy way to do this?
converting mysql time to epoch: ``` >>> import time >>> import calendar >>> mysql_time = "2010-01-02 03:04:05" >>> mysql_time_struct = time.strptime(mysql_time, '%Y-%m-%d %H:%M:%S') >>> print mysql_time_struct (2010, 1, 2, 3, 4, 5, 5, 2, -1) >>> mysql_time_epoch = calendar.timegm(mysql_time_struct) >>> print mysql_time_epoch 1262401445 ``` converting epoch to something MySQL can use: ``` >>> import time >>> time_epoch = time.time() >>> print time_epoch 1268121070.7 >>> time_struct = time.gmtime(time_epoch) >>> print time_struct (2010, 3, 9, 7, 51, 10, 1, 68, 0) >>> time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time_struct) >>> print time_formatted 2010-03-09 07:51:10 ```
What would be the simplest way to daemonize a python script in Linux?
115,974
10
2008-09-22T16:39:09Z
116,035
20
2008-09-22T16:47:31Z
[ "python", "scripting", "daemon" ]
What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools.
See [Stevens](http://www.kohala.com/start/) and also this [lengthy thread on activestate](http://code.activestate.com/recipes/278731/) which I found personally to be both mostly incorrect and much to verbose, and I came up with this: ``` from os import fork, setsid, umask, dup2 from sys import stdin, stdout, stderr if fork(): exit(0) umask(0) setsid() if fork(): exit(0) stdout.flush() stderr.flush() si = file('/dev/null', 'r') so = file('/dev/null', 'a+') se = file('/dev/null', 'a+', 0) dup2(si.fileno(), stdin.fileno()) dup2(so.fileno(), stdout.fileno()) dup2(se.fileno(), stderr.fileno()) ``` If you need to stop that process again, it is required to know the pid, the usual solution to this is pidfiles. Do this if you need one ``` from os import getpid outfile = open(pid_file, 'w') outfile.write('%i' % getpid()) outfile.close() ``` For security reasons you might consider any of these after demonizing ``` from os import setuid, setgid, chdir from pwd import getpwnam from grp import getgrnam setuid(getpwnam('someuser').pw_uid) setgid(getgrnam('somegroup').gr_gid) chdir('/') ``` You could also use [nohup](http://en.wikipedia.org/wiki/Nohup) but that does not work well with [python's subprocess module](http://docs.python.org/lib/module-subprocess.html)
Using Pylint with Django
115,977
89
2008-09-22T16:39:34Z
116,025
15
2008-09-22T16:46:00Z
[ "python", "django", "static-analysis", "pylint" ]
I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for my python projects, but I have run into one show-stopper: One of the error types that I find extremely useful--:`E1101: *%s %r has no %r member*`--constantly reports errors when using common django fields, for example: ``` E1101:125:get_user_tags: Class 'Tag' has no 'objects' member ``` which is caused by this code: ``` def get_user_tags(username): """ Gets all the tags that username has used. Returns a query set. """ return Tag.objects.filter( ## This line triggers the error. tagownership__users__username__exact=username).distinct() # Here is the Tag class, models.Model is provided by Django: class Tag(models.Model): """ Model for user-defined strings that help categorize Events on on a per-user basis. """ name = models.CharField(max_length=500, null=False, unique=True) def __unicode__(self): return self.name ``` How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of `objects`, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.) **Edit:** The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :) See [here](http://creswick.github.io/blog/2008/09/05/wrestling-python/) for a summary of the problems I've had with `pychecker` and `pyflakes` -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)
Because of how pylint works (it examines the source itself, without letting Python actually execute it) it's very hard for pylint to figure out how metaclasses and complex baseclasses actually affect a class and its instances. The 'pychecker' tool is a bit better in this regard, because it *does* actually let Python execute the code; it imports the modules and examines the resulting objects. However, that approach has other problems, because it does actually let Python execute the code :-) You could extend pylint to teach it about the magic Django uses, or to make it understand metaclasses or complex baseclasses better, or to just ignore such cases after detecting one or more features it doesn't quite understand. I don't think it would be particularly easy. You can also just tell pylint to not warn about these things, through special comments in the source, command-line options or a .pylintrc file.
Using Pylint with Django
115,977
89
2008-09-22T16:39:34Z
118,375
7
2008-09-23T00:17:58Z
[ "python", "django", "static-analysis", "pylint" ]
I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for my python projects, but I have run into one show-stopper: One of the error types that I find extremely useful--:`E1101: *%s %r has no %r member*`--constantly reports errors when using common django fields, for example: ``` E1101:125:get_user_tags: Class 'Tag' has no 'objects' member ``` which is caused by this code: ``` def get_user_tags(username): """ Gets all the tags that username has used. Returns a query set. """ return Tag.objects.filter( ## This line triggers the error. tagownership__users__username__exact=username).distinct() # Here is the Tag class, models.Model is provided by Django: class Tag(models.Model): """ Model for user-defined strings that help categorize Events on on a per-user basis. """ name = models.CharField(max_length=500, null=False, unique=True) def __unicode__(self): return self.name ``` How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of `objects`, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.) **Edit:** The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :) See [here](http://creswick.github.io/blog/2008/09/05/wrestling-python/) for a summary of the problems I've had with `pychecker` and `pyflakes` -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)
This is not a solution, but you can add `objects = models.Manager()` to your Django models without changing any behavior. I myself only use pyflakes, primarily due to some dumb defaults in pylint and laziness on my part (not wanting to look up how to change the defaults).
Using Pylint with Django
115,977
89
2008-09-22T16:39:34Z
1,416,297
59
2009-09-12T22:21:47Z
[ "python", "django", "static-analysis", "pylint" ]
I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for my python projects, but I have run into one show-stopper: One of the error types that I find extremely useful--:`E1101: *%s %r has no %r member*`--constantly reports errors when using common django fields, for example: ``` E1101:125:get_user_tags: Class 'Tag' has no 'objects' member ``` which is caused by this code: ``` def get_user_tags(username): """ Gets all the tags that username has used. Returns a query set. """ return Tag.objects.filter( ## This line triggers the error. tagownership__users__username__exact=username).distinct() # Here is the Tag class, models.Model is provided by Django: class Tag(models.Model): """ Model for user-defined strings that help categorize Events on on a per-user basis. """ name = models.CharField(max_length=500, null=False, unique=True) def __unicode__(self): return self.name ``` How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of `objects`, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.) **Edit:** The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :) See [here](http://creswick.github.io/blog/2008/09/05/wrestling-python/) for a summary of the problems I've had with `pychecker` and `pyflakes` -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)
I use the following: `pylint --generated-members=objects`
Using Pylint with Django
115,977
89
2008-09-22T16:39:34Z
2,456,436
18
2010-03-16T17:00:16Z
[ "python", "django", "static-analysis", "pylint" ]
I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for my python projects, but I have run into one show-stopper: One of the error types that I find extremely useful--:`E1101: *%s %r has no %r member*`--constantly reports errors when using common django fields, for example: ``` E1101:125:get_user_tags: Class 'Tag' has no 'objects' member ``` which is caused by this code: ``` def get_user_tags(username): """ Gets all the tags that username has used. Returns a query set. """ return Tag.objects.filter( ## This line triggers the error. tagownership__users__username__exact=username).distinct() # Here is the Tag class, models.Model is provided by Django: class Tag(models.Model): """ Model for user-defined strings that help categorize Events on on a per-user basis. """ name = models.CharField(max_length=500, null=False, unique=True) def __unicode__(self): return self.name ``` How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of `objects`, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.) **Edit:** The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :) See [here](http://creswick.github.io/blog/2008/09/05/wrestling-python/) for a summary of the problems I've had with `pychecker` and `pyflakes` -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)
django-lint is a nice tool which wraps pylint with django specific settings : <http://chris-lamb.co.uk/projects/django-lint/> github project: <https://github.com/lamby/django-lint>
Using Pylint with Django
115,977
89
2008-09-22T16:39:34Z
4,162,971
27
2010-11-12T08:59:11Z
[ "python", "django", "static-analysis", "pylint" ]
I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for my python projects, but I have run into one show-stopper: One of the error types that I find extremely useful--:`E1101: *%s %r has no %r member*`--constantly reports errors when using common django fields, for example: ``` E1101:125:get_user_tags: Class 'Tag' has no 'objects' member ``` which is caused by this code: ``` def get_user_tags(username): """ Gets all the tags that username has used. Returns a query set. """ return Tag.objects.filter( ## This line triggers the error. tagownership__users__username__exact=username).distinct() # Here is the Tag class, models.Model is provided by Django: class Tag(models.Model): """ Model for user-defined strings that help categorize Events on on a per-user basis. """ name = models.CharField(max_length=500, null=False, unique=True) def __unicode__(self): return self.name ``` How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of `objects`, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.) **Edit:** The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :) See [here](http://creswick.github.io/blog/2008/09/05/wrestling-python/) for a summary of the problems I've had with `pychecker` and `pyflakes` -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)
My ~/.pylintrc contains ``` [TYPECHECK] generated-members=REQUEST,acl_users,aq_parent,objects,_meta,id ``` the last two are specifically for Django. Note that there is a [bug in PyLint 0.21.1](http://www.logilab.org/ticket/28796) which needs patching to make this work. Edit: After messing around with this a little more, I decided to hack PyLint just a tiny bit to allow me to expand the above into: ``` [TYPECHECK] generated-members=REQUEST,acl_users,aq_parent,objects,_meta,id,[a-zA-Z]+_set ``` I simply added: ``` import re for pattern in self.config.generated_members: if re.match(pattern, node.attrname): return ``` after the fix mentioned in the bug report (i.e., at line 129). Happy days!
Using Pylint with Django
115,977
89
2008-09-22T16:39:34Z
31,000,713
31
2015-06-23T10:47:45Z
[ "python", "django", "static-analysis", "pylint" ]
I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for my python projects, but I have run into one show-stopper: One of the error types that I find extremely useful--:`E1101: *%s %r has no %r member*`--constantly reports errors when using common django fields, for example: ``` E1101:125:get_user_tags: Class 'Tag' has no 'objects' member ``` which is caused by this code: ``` def get_user_tags(username): """ Gets all the tags that username has used. Returns a query set. """ return Tag.objects.filter( ## This line triggers the error. tagownership__users__username__exact=username).distinct() # Here is the Tag class, models.Model is provided by Django: class Tag(models.Model): """ Model for user-defined strings that help categorize Events on on a per-user basis. """ name = models.CharField(max_length=500, null=False, unique=True) def __unicode__(self): return self.name ``` How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of `objects`, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.) **Edit:** The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :) See [here](http://creswick.github.io/blog/2008/09/05/wrestling-python/) for a summary of the problems I've had with `pychecker` and `pyflakes` -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)
Do not disable or weaken Pylint functionality by adding `ignores` or `generated-members`. Use an actively developed Pylint plugin that **understands** Django. [This Pylint plugin for Django](https://github.com/landscapeio/pylint-django) works quite well: ``` pip install pylint-django ``` and when running pylint add the following flag to the command: ``` --load-plugins pylint_django ``` Detailed blog post [here](https://blog.landscape.io/using-pylint-on-django-projects-with-pylint-django.html).
How can I search a word in a Word 2007 .docx file?
116,139
40
2008-09-22T17:08:12Z
116,217
30
2008-09-22T17:22:10Z
[ "python", "ms-word", "openxml", "docx" ]
I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".
More exactly, a .docx document is a Zip archive in OpenXML format: you have first to uncompress it. I downloaded a sample (Google: *some search term filetype:docx*) and after unzipping I found some folders. The *word* folder contains the document itself, in file *document.xml*.
How can I search a word in a Word 2007 .docx file?
116,139
40
2008-09-22T17:08:12Z
118,175
14
2008-09-22T23:12:59Z
[ "python", "ms-word", "openxml", "docx" ]
I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".
In this example, "Course Outline.docx" is a Word 2007 document, which does contain the word "Windows", and does not contain the phrase "random other string". ``` >>> import zipfile >>> z = zipfile.ZipFile("Course Outline.docx") >>> "Windows" in z.read("word/document.xml") True >>> "random other string" in z.read("word/document.xml") False >>> z.close() ``` Basically, you just open the docx file (which is a zip archive) using [zipfile](http://docs.python.org/lib/module-zipfile.html), and find the content in the 'document.xml' file in the 'word' folder. If you wanted to be more sophisticated, you could then [parse the XML](http://docs.python.org/lib/module-xml.etree.ElementTree.html), but if you're just looking for a phrase (which you know won't be a tag), then you can just look in the XML for the string.
How can I search a word in a Word 2007 .docx file?
116,139
40
2008-09-22T17:08:12Z
1,737,242
13
2009-11-15T11:01:08Z
[ "python", "ms-word", "openxml", "docx" ]
I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".
A problem with searching inside a Word document XML file is that the text can be split into elements at any character. It will certainly be split if formatting is different, for example as in Hello **World**. But it *can* be split at any point and that is valid in OOXML. So you will end up dealing with XML like this even if formatting does not change in the middle of the phrase! ``` <w:p w:rsidR="00C07F31" w:rsidRDefault="003F6D7A"> <w:r w:rsidRPr="003F6D7A"> <w:rPr> <w:b /> </w:rPr> <w:t>Hello</w:t> </w:r> <w:r> <w:t xml:space="preserve">World.</w:t> </w:r> </w:p> ``` You can of course load it into an XML DOM tree (not sure what this will be in Python) and ask to get text only as a string, but you could end up with many other "dead ends" just because the OOXML spec is around 6000 pages long and MS Word can write lots of "stuff" you don't expect. So you could end up writing your own document processing library. Or you can try using [Aspose.Words](http://www.aspose.com/categories/.net-components/aspose.words-for-.net/default.aspx). It is available as .NET and Java products. Both can be used from Python. One via COM Interop another via JPype. See Aspose.Words Programmers Guide, Utilize Aspose.Words in Other Programming Languages (sorry I can't post a second link, stackoverflow does not let me yet).
How can I search a word in a Word 2007 .docx file?
116,139
40
2008-09-22T17:08:12Z
1,979,864
127
2009-12-30T12:08:33Z
[ "python", "ms-word", "openxml", "docx" ]
I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".
After reading your post above, I made a 100% native Python docx module to solve this specific problem. ``` # Import the module from docx import * # Open the .docx file document = opendocx('A document.docx') # Search returns true if found search(document,'your search string') ``` The docx module is at <https://python-docx.readthedocs.org/en/latest/>
How do you create an osx application/dmg from a python package?
116,657
23
2008-09-22T18:35:28Z
116,901
7
2008-09-22T19:19:30Z
[ "python", "osx", "packaging" ]
I want to create a mac osx application from python package and then put it in a disk image. Because I load some resources out of the package, the package should **not** reside in a zip file. The resulting disk image should display the background picture to "drag here -> applications" for installation.
I don't know the correct way to do it, but this manual method is the approach I've used for simple scripts which seems to have preformed suitably. I'll assume that whatever directory I'm in, the Python files for my program are in the relative `src/` directory, and that the file I want to execute (which has the proper shebang and execute permissions) is named `main.py`. ``` $ mkdir -p MyApplication.app/Contents/MacOS $ mv src/* MyApplication.app/Contents/MacOS $ cd MyApplication.app/Contents/MacOS $ mv main.py MyApplication ``` At this point we have an application bundle which, as far as I know, should work on any Mac OS system with Python installed (which I think it has by default). It doesn't have an icon or anything, that requires adding some more metadata to the package which is unnecessary for my purposes and I'm not familiar with. To create the drag-and-drop installer is quite simple. Use Disk Utility to create a New Disk Image of approximately the size you require to store your application. Open it up, copy your application and an alias of `/Applications` to the drive, then use View Options to position them as you want. The drag-and-drop message is just a background of the disk image, which you can also specify in View Options. I haven't done it before, but I'd assume that after you whip up an image in your editor of choice you could copy it over, set it as the background and then use `chflags hidden` to prevent it from cluttering up your nice window. I know these aren't the clearest, simplest or most detailed instructions out there, but I hope somebody may find them useful.
How to Retrieve name of current Windows User (AD or local) using Python?
117,014
18
2008-09-22T19:36:32Z
117,047
26
2008-09-22T19:42:41Z
[ "python", "active-directory" ]
How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.
Try this: ``` import os; print os.environ.get( "USERNAME" ) ``` That should do the job.
Python and POST data
117,167
4
2008-09-22T19:57:37Z
117,201
10
2008-09-22T20:01:12Z
[ "python", "http", "post" ]
In PHP I simply write: ``` $bob = $_POST['bob']; ``` How do I do the same in Python? And yes, I do normally check that it exists etc, I'm just stripping it down specifically to the functionality I am after. --- Edit: I am not using a framework
The simplest method is the 'cgi' module: ``` import cgi data = cgi.FieldStorage() data['bob'] ``` But the context you are executing in (frameworks you're using, WSGI or even (heaven forbid) mod\_python) may have different, more efficient or more direct methods of access.
How do I get a decimal value when using the division operator in Python?
117,250
31
2008-09-22T20:06:16Z
117,264
79
2008-09-22T20:08:15Z
[ "python", "math", "syntax", "operators" ]
For example, the standard division symbol '/' rounds to zero: ``` >>> 4 / 100 0 ``` However, I want it to return 0.04. What do I use?
There are three options: ``` >>> 4 / float(100) 0.04 >>> 4 / 100.0 0.04 ``` which is the same behavior as the C, C++, Java etc, or ``` >>> from __future__ import division >>> 4 / 100 0.04 ``` You can also activate this behavior by passing the argument `-Qnew` to the Python interpreter: ``` $ python -Qnew >>> 4 / 100 0.04 ``` The second option will be the default in Python 3.0. If you want to have the old integer division, you have to use the `//` operator. **Edit**: added section about `-Qnew`, thanks to [ΤΖΩΤΖΙΟΥ](http://stackoverflow.com/users/6899/)!
How do I get a decimal value when using the division operator in Python?
117,250
31
2008-09-22T20:06:16Z
117,270
7
2008-09-22T20:08:45Z
[ "python", "math", "syntax", "operators" ]
For example, the standard division symbol '/' rounds to zero: ``` >>> 4 / 100 0 ``` However, I want it to return 0.04. What do I use?
Make one or both of the terms a floating point number, like so: ``` 4.0/100.0 ``` Alternatively, turn on the feature that will be default in Python 3.0, 'true division', that does what you want. At the top of your module or script, do: ``` from __future__ import division ```
How do I get a decimal value when using the division operator in Python?
117,250
31
2008-09-22T20:06:16Z
117,682
21
2008-09-22T21:12:07Z
[ "python", "math", "syntax", "operators" ]
For example, the standard division symbol '/' rounds to zero: ``` >>> 4 / 100 0 ``` However, I want it to return 0.04. What do I use?
Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact: ``` >>> 0.4/100. 0.0040000000000000001 ``` If you actually want a *decimal* value, do this: ``` >>> import decimal >>> decimal.Decimal('4') / decimal.Decimal('100') Decimal("0.04") ``` That will give you an object that properly knows that 4 / 100 in *base 10* is "0.04". Floating-point numbers are actually in base 2, i.e. binary, not decimal.
What's the Name of the Python Module that Formats arbitrary Text to nicely looking HTML?
117,477
10
2008-09-22T20:39:11Z
117,824
14
2008-09-22T21:41:26Z
[ "python", "formatting", "markup" ]
A while ago I came across a Python library that formats regular text to HTML similar to Markdown, reStructuredText and Textile, just that it had no syntax at all. It detected indentatations, quotes, links and newlines/paragraphs only. Unfortunately I lost the name of the library and was unable to Google it. Anyone any ideas? **Edit:** reStructuredText aka rst == docutils. That's not what I'm looking for :)
Okay. I found it now. It's called [PottyMouth](http://glyphobet.net/pottymouth/).
How do I use timezones with a datetime object in python?
117,514
37
2008-09-22T20:44:39Z
117,523
9
2008-09-22T20:46:08Z
[ "python", "datetime", "timezone" ]
How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone() ``` import datetime, re from datetime import tzinfo class myTimeZone(tzinfo): """docstring for myTimeZone""" def utfoffset(self, dt): return timedelta(hours=1) def myDateHandler(aDateString): """u'Sat, 6 Sep 2008 21:16:33 EDT'""" _my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)') day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups() month = [ 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC' ].index(month.upper()) + 1 dt = datetime.datetime( int(year), int(month), int(day), int(hour), int(minute), int(second) ) # dt = dt - datetime.timedelta(hours=1) # dt = dt - dt.tzinfo.utfoffset(myTimeZone()) return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0) def main(): print myDateHandler("Sat, 6 Sep 2008 21:16:33 EDT") if __name__ == '__main__': main() ```
The Python standard library doesn't contain timezone information, because unfortunately timezone data changes a lot faster than Python. You need a third-party module for this; the usual choice is [pytz](http://pytz.sourceforge.net)
How do I use timezones with a datetime object in python?
117,514
37
2008-09-22T20:44:39Z
117,615
36
2008-09-22T20:59:40Z
[ "python", "datetime", "timezone" ]
How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone() ``` import datetime, re from datetime import tzinfo class myTimeZone(tzinfo): """docstring for myTimeZone""" def utfoffset(self, dt): return timedelta(hours=1) def myDateHandler(aDateString): """u'Sat, 6 Sep 2008 21:16:33 EDT'""" _my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)') day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups() month = [ 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC' ].index(month.upper()) + 1 dt = datetime.datetime( int(year), int(month), int(day), int(hour), int(minute), int(second) ) # dt = dt - datetime.timedelta(hours=1) # dt = dt - dt.tzinfo.utfoffset(myTimeZone()) return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0) def main(): print myDateHandler("Sat, 6 Sep 2008 21:16:33 EDT") if __name__ == '__main__': main() ```
I recommend `babel` and `pytz` when working with timezones. Keep your internal datetime objects naive and in UTC and convert to your timezone for formatting only. The reason why you probably want naive objects (objects without timezone information) is that many libraries and database adapters have no idea about timezones. * [Babel](http://babel.pocoo.org/) * [pytz](http://pytz.sourceforge.net/)
How do I use timezones with a datetime object in python?
117,514
37
2008-09-22T20:44:39Z
1,893,437
7
2009-12-12T13:35:12Z
[ "python", "datetime", "timezone" ]
How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone() ``` import datetime, re from datetime import tzinfo class myTimeZone(tzinfo): """docstring for myTimeZone""" def utfoffset(self, dt): return timedelta(hours=1) def myDateHandler(aDateString): """u'Sat, 6 Sep 2008 21:16:33 EDT'""" _my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)') day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups() month = [ 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC' ].index(month.upper()) + 1 dt = datetime.datetime( int(year), int(month), int(day), int(hour), int(minute), int(second) ) # dt = dt - datetime.timedelta(hours=1) # dt = dt - dt.tzinfo.utfoffset(myTimeZone()) return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0) def main(): print myDateHandler("Sat, 6 Sep 2008 21:16:33 EDT") if __name__ == '__main__': main() ```
For the current local timezone, you can you use: ``` >>> import time >>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone >>> offset / 60 / 60 * -1 -9 ``` The value returned is in seconds West of UTC (with areas East of UTC getting a negative value). This is the opposite to how we'd actually like it, hence the `* -1`. `localtime().tm_isdst` will be zero if daylight savings is currently not in effect (although this may not be correct if an area has recently changed their daylight savings law).
How can i parse a comma delimited string into a list (caveat)?
118,096
19
2008-09-22T22:54:10Z
118,162
39
2008-09-22T23:09:45Z
[ "python", "split", "escaping", "quotes" ]
I need to be able to take a string like: ``` '''foo, bar, "one, two", three four''' ``` into: ``` ['foo', 'bar', 'one, two', 'three four'] ``` I have an feeling (with hints from #python) that the solution is going to involve the shlex module.
It depends how complicated you want to get... do you want to allow more than one type of quoting. How about escaped quotes? Your syntax looks very much like the common CSV file format, which is supported by the Python standard library: ``` import csv reader = csv.reader(['''foo, bar, "one, two", three four'''], skipinitialspace=True) for r in reader: print r ``` Outputs: ``` ['foo', 'bar', 'one, two', 'three four'] ``` HTH!
How can i parse a comma delimited string into a list (caveat)?
118,096
19
2008-09-22T22:54:10Z
118,187
21
2008-09-22T23:15:45Z
[ "python", "split", "escaping", "quotes" ]
I need to be able to take a string like: ``` '''foo, bar, "one, two", three four''' ``` into: ``` ['foo', 'bar', 'one, two', 'three four'] ``` I have an feeling (with hints from #python) that the solution is going to involve the shlex module.
The shlex module solution allows escaped quotes, one quote escape another, and all fancy stuff shell supports. ``` >>> import shlex >>> my_splitter = shlex.shlex('''foo, bar, "one, two", three four''', posix=True) >>> my_splitter.whitespace += ',' >>> my_splitter.whitespace_split = True >>> print list(my_splitter) ['foo', 'bar', 'one, two', 'three', 'four'] ``` escaped quotes example: ``` >>> my_splitter = shlex.shlex('''"test, a",'foo,bar",baz',bar \xc3\xa4 baz''', posix=True) >>> my_splitter.whitespace = ',' ; my_splitter.whitespace_split = True >>> print list(my_splitter) ['test, a', 'foo,bar",baz', 'bar \xc3\xa4 baz'] ```
Python Regex vs PHP Regex
118,143
3
2008-09-22T23:06:02Z
118,163
7
2008-09-22T23:10:13Z
[ "php", "python", "regex" ]
No not a competition, it is instead me trying to find why a certain regex works in one but not the other. ``` (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) ``` That's my Regex and I'm trying to run it on ``` 127.255.0.0 ``` Using Pythons regex I get nothing, using PHP I match it, below are the two calls I am making (just incase it's something to do with that). Essentially I am trying to work out why it works in PHP but not Python. ``` re.findall(regex, string) preg_match_all($regex, $string, $matches); ``` --- Solution found, it was due to the way that I was iterating through the results, this regex turned them into groups and then it didn't want to print them out in the same way etc etc. Thank you all for your help, it's really appreciated :)
It works for me. You must be doing something wrong. ``` >>> re.match(r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', '127.255.0.0').groups() ('127', '255', '0', '0') ``` Don't forget to escape the regex using raw strings: `r'regex_here'` as stated in the [Regex Howto](http://docs.python.org/dev/howto/regex.html)
How to start IDLE (Python editor) without using the shortcut on Windows Vista?
118,260
43
2008-09-22T23:44:21Z
118,275
53
2008-09-22T23:49:11Z
[ "python", "python-idle", "komodo", "pywin" ]
I'm trying to teach Komodo to fire up [IDLE](http://en.wikipedia.org/wiki/IDLE%5F%28Python%29) when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up. I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out. How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.
There's a file called idle.py in your Python installation directory in Lib\idlelib\idle.py If you run that file with Python, then IDLE should start. > c:\Python25\pythonw.exe c:\Python25\Lib\idlelib\idle.py
How to start IDLE (Python editor) without using the shortcut on Windows Vista?
118,260
43
2008-09-22T23:44:21Z
118,308
8
2008-09-22T23:56:03Z
[ "python", "python-idle", "komodo", "pywin" ]
I'm trying to teach Komodo to fire up [IDLE](http://en.wikipedia.org/wiki/IDLE%5F%28Python%29) when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up. I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out. How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.
Here's another path you can use. I'm not sure if this is part of the standard distribution or if the file is automatically created on first use of the IDLE. ``` C:\Python25\Lib\idlelib\idle.pyw ```
How to start IDLE (Python editor) without using the shortcut on Windows Vista?
118,260
43
2008-09-22T23:44:21Z
7,394,470
10
2011-09-12T21:48:51Z
[ "python", "python-idle", "komodo", "pywin" ]
I'm trying to teach Komodo to fire up [IDLE](http://en.wikipedia.org/wiki/IDLE%5F%28Python%29) when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up. I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out. How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.
In Python 3.2.2, I found `\Python32\Lib\idlelib\idle.bat` which was useful because it would let me open python files supplied as args in IDLE.
How to start IDLE (Python editor) without using the shortcut on Windows Vista?
118,260
43
2008-09-22T23:44:21Z
8,237,399
8
2011-11-23T04:35:54Z
[ "python", "python-idle", "komodo", "pywin" ]
I'm trying to teach Komodo to fire up [IDLE](http://en.wikipedia.org/wiki/IDLE%5F%28Python%29) when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up. I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out. How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.
If you just have a Python shell running, type: ``` import idlelib.PyShell idlelib.PyShell.main() ```
How do you use the ellipsis slicing syntax in Python?
118,370
114
2008-09-23T00:17:09Z
118,395
70
2008-09-23T00:24:21Z
[ "python", "numpy", "subclass", "slice", "ellipsis" ]
This came up in [Hidden features of Python](http://stackoverflow.com/questions/101268/hidden-features-of-python), but I can't see good documentation or examples that explain how the feature works.
You'd use it in your own class, since no builtin class makes use of it. Numpy uses it, as stated in the [documentation](http://wiki.scipy.org/Numpy_Example_List_With_Doc#head-490d781b49b68b300eedaef32369fae7d58627fb). Some examples [here](http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-864862d3f2bb4c32f04260fac61eb4ef34788c4c). In your own class, you'd use it like this: ``` >>> class TestEllipsis(object): ... def __getitem__(self, item): ... if item is Ellipsis: ... return "Returning all items" ... else: ... return "return %r items" % item ... >>> x = TestEllipsis() >>> print x[2] return 2 items >>> print x[...] Returning all items ``` Of course, there is the [python documentation](https://docs.python.org/library/constants.html#Ellipsis), and [language reference](https://docs.python.org/reference/expressions.html#grammar-token-slicing). But those aren't very helpful.
How do you use the ellipsis slicing syntax in Python?
118,370
114
2008-09-23T00:17:09Z
118,508
159
2008-09-23T00:55:09Z
[ "python", "numpy", "subclass", "slice", "ellipsis" ]
This came up in [Hidden features of Python](http://stackoverflow.com/questions/101268/hidden-features-of-python), but I can't see good documentation or examples that explain how the feature works.
The ellipsis is used to slice higher-dimensional data structures. It's designed to mean *at this point, insert as many full slices (`:`) to extend the multi-dimensional slice to all dimensions*. **Example**: ``` >>> from numpy import arange >>> a = arange(16).reshape(2,2,2,2) ``` Now, you have a 4-dimensional matrix of order 2x2x2x2. To select all first elements in the 4th dimension, you can use the ellipsis notation ``` >>> a[..., 0].flatten() array([ 0, 2, 4, 6, 8, 10, 12, 14]) ``` which is equivalent to ``` >>> a[:,:,:,0].flatten() array([ 0, 2, 4, 6, 8, 10, 12, 14]) ``` In your own implementations, you're free to ignore the contract mentioned above and use it for whatever you see fit.
How do you use the ellipsis slicing syntax in Python?
118,370
114
2008-09-23T00:17:09Z
120,055
66
2008-09-23T09:34:48Z
[ "python", "numpy", "subclass", "slice", "ellipsis" ]
This came up in [Hidden features of Python](http://stackoverflow.com/questions/101268/hidden-features-of-python), but I can't see good documentation or examples that explain how the feature works.
This is another use for Ellipsis, which has nothing to do with slices: I often use it in intra-thread communication with queues, as a mark that signals "Done"; it's there, it's an object, it's a singleton, and its name means "lack of", and it's not the overused None (which could be put in a queue as part of normal data flow). YMMV. P.S: I don't mind downvotes, when what I say in an answer is not useful in relation to the question; then I try to improve my answer. But I sure can't understand how one can downvote *any* of the answers in this question— when the question is “how do *you* use the Ellipsis in Python”… It seems that people think that downvoting means “I disagree” or “I don't like this”.
How can I join a list into a string (caveat)?
118,458
6
2008-09-23T00:41:25Z
118,462
7
2008-09-23T00:43:42Z
[ "python", "string", "list", "csv" ]
Along the lines of my previous [question](http://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat), how can i join a list of strings into a string such that values get quoted cleanly. Something like: ``` ['a', 'one "two" three', 'foo, bar', """both"'"""] ``` into: ``` a, 'one "two" three', "foo, bar", "both\"'" ``` I suspect that the csv module will come into play here, but i'm not sure how to get the output I want.
Using the `csv` module you can do that way: ``` import csv writer = csv.writer(open("some.csv", "wb")) writer.writerow(the_list) ``` If you need a string just use `StringIO` instance as a file: ``` f = StringIO.StringIO() writer = csv.writer(f) writer.writerow(the_list) print f.getvalue() ``` The output: `a,"one ""two"" three","foo, bar","both""'"` `csv` will write in a way it can read back later. You can fine-tune its output by defining a `dialect`, just set `quotechar`, `escapechar`, etc, as needed: ``` class SomeDialect(csv.excel): delimiter = ',' quotechar = '"' escapechar = "\\" doublequote = False lineterminator = '\n' quoting = csv.QUOTE_MINIMAL f = cStringIO.StringIO() writer = csv.writer(f, dialect=SomeDialect) writer.writerow(the_list) print f.getvalue() ``` The output: `a,one \"two\" three,"foo, bar",both\"'` The same dialect can be used with csv module to read the string back later to a list.
How do I read an Excel file into Python using xlrd? Can it read newer Office formats?
118,516
10
2008-09-23T00:58:09Z
694,688
25
2009-03-29T14:21:13Z
[ "python", "xlrd", "import-from-excel" ]
My issue is below but would be interested comments from anyone with experience with xlrd. I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <http://www.djindexes.com/mdsidx/?event=showAverages>) When I open the file unmodified I get a nasty BIFF error (binary format not recognized) However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <http://skitch.com/alok/ssa3/componentreport-dji.xls-properties>) If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls Here is a pastebin of an ipython session replicating the issue: <http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq> Any thoughts on: How to trick xlrd into recognizing the file so I can extract data? How to use python to automate the explicit 'save as' format to one that xlrd will accept? Plan B?
FWIW, I'm the author of xlrd, and the maintainer of xlwt (a fork of pyExcelerator). A few points: 1. The file ComponentReport-DJI.xls is misnamed; it is not an XLS file, it is a tab-separated-values file. Open it with a text editor (e.g. Notepad) and you'll see what I mean. You can also look at the not-very-raw raw bytes with Python: ``` >>> open('ComponentReport-DJI.xls', 'rb').read(200) 'COMPANY NAME\tPRIMARY EXCHANGE\tTICKER\tSTYLE\tICB SUBSECTOR\tMARKET CAP RANGE\ tWEIGHT PCT\tUSD CLOSE\t\r\n3M Co.\tNew York SE\tMMM\tN/A\tDiversified Industria ls\tBroad\t5.15676229508\t50.33\t\r\nAlcoa Inc.\tNew York SE\tA' ``` You can read this file using Python's csv module ... just use `delimiter="\t"` in your call to `csv.reader()`. 2. xlrd can read any file that pyExcelerator can, and read them better—dates don't come out as floats, and the full story on Excel dates is in the xlrd documentation. 3. pyExcelerator is abandonware—xlrd and xlwt are alive and well. Check out <http://groups.google.com/group/python-excel> HTH John
Is there a way to convert indentation in Python code to braces?
118,643
73
2008-09-23T01:33:13Z
118,651
10
2008-09-23T01:35:23Z
[ "python", "accessibility", "blind", "blindness" ]
I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?
I personally doubt that there currently is at the moment, as a lot of the Python afficionados love the fact that Python is this way, whitespace delimited. I've never actually thought about that as an accessibility issue however. Maybe it's something to put forward as a bug report to Python? I'd assume that you use a screen reader here however for the output? So the tabs would seem "invisible" to you? With a Braille output, it might be easier to read, but I can understand exactly how confusing this could be. In fact, this is very interesting to me. I wish that I knew enough to be able to write an app that will do this for you. I think it's definately something that I'll put in a bug report for, unless you've already done so yourself, or want to. Edit: Also, as [noted](http://stackoverflow.com/questions/118643#118656) by [John Millikin](http://stackoverflow.com/users/3560/john-millikin) There is also [PyBraces](http://timhatch.com/projects/pybraces/) Which might be a viable solution to you, and may be possible to be hacked together dependant on your coding skills to be exactly what you need (and I hope that if that's the case, you release it out for others like yourself to use) Edit 2: I've just [reported this](http://bugs.python.org/issue3942) to the python bug tracker
Is there a way to convert indentation in Python code to braces?
118,643
73
2008-09-23T01:33:13Z
118,706
9
2008-09-23T01:51:53Z
[ "python", "accessibility", "blind", "blindness" ]
I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?
Although I am not blind, I have heard good things about [Emacspeak](http://emacspeak.sourceforge.net/). They've had a Python mode since their [8.0 release](http://emacspeak.sourceforge.net/releases/release-8.0.html) in 1998 (they seem to be up to release 28.0!). Definitely worth checking out.
Is there a way to convert indentation in Python code to braces?
118,643
73
2008-09-23T01:33:13Z
118,738
24
2008-09-23T02:02:25Z
[ "python", "accessibility", "blind", "blindness" ]
I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?
Python supports braces for defining code blocks, and it also supports using 'begin' and 'end' tags. Please see these code examples: ``` class MyClass(object): #{ def myfunction(self, arg1, arg2): #{ for i in range(arg1): #{ print i #} #} #} ``` And an example with bash style: ``` fi = endclass = enddef = endclass = done = None class MyClass(object): def myfunction(self, arg1, arg2): for i in range(arg1): #do if i > 5: #then print i fi done enddef endclass ``` The best thing about this is is that you can forget to put a close bracket in, and it's still valid python! ``` class MyClass(object): #{ def myfunction(self, arg1, arg2): #{ for i in range(arg1): #{ print i # whoops, forgot to close that bracket! #} #} ``` [original gag](http://www.python.org/doc/humor/#python-block-delimited-notation-parsing-explained) My real advice is to get a Braille display if you can afford one/source one - blind python programmers of my acquaintance really found a Braille display indispensable for writing python programs, it makes the indentation thing much less painful. A 40 cell display is well worth it.
Is there a way to convert indentation in Python code to braces?
118,643
73
2008-09-23T01:33:13Z
118,744
52
2008-09-23T02:04:01Z
[ "python", "accessibility", "blind", "blindness" ]
I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?
There's a solution to your problem that is distributed with python itself. `pindent.py`, it's located in the Tools\Scripts directory in a windows install (my path to it is C:\Python25\Tools\Scripts), it looks like you'd have grab it from svn.python.org if you are running on Linux or OSX. It adds comments when blocks are closed, or can properly indent code if comments are put in. Here's an example of the code outputted by pindent with the command: `pindent -c myfile.py` ``` def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 # end if else: print 'oops!' # end if # end def foobar ``` Where the original `myfile.py` was: ``` def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 else: print 'oops!' ``` You can also use `pindent.py -d` to insert the correct indentation based on comments (read the header of pindent.py for details), this should allow you to code in python without worrying about indentation. I'd be interested to learn what solution you end up using, if you require any further assistance, please comment on this post and I'll try to help.
Iron python, beautiful soup, win32 app
118,654
20
2008-09-23T01:37:48Z
118,713
8
2008-09-23T01:53:58Z
[ ".net", "python", "ironpython" ]
Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)?
I've tested and used BeautifulSoup with both IPy 1.1 and 2.0 (forget which beta, but this was a few months back). Leave a comment if you are still having trouble and I'll dig out my test code and post it.