title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
Sending mail from Python using SMTP
64,505
<p>I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?</p> <pre><code>from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "John Doe &lt;[email protected]&gt;" to_addr = "[email protected]" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() </code></pre>
70
2008-09-15T16:36:35Z
64,890
<p>The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.</p> <p>I rely on my ISP to add the date time header.</p> <p>My ISP requires me to use a secure smtp connection to send mail, I rely on the ssmtplib module (downloadable at <a href="http://www1.cs.columbia.edu/~db2501/ssmtplib.py" rel="nofollow">http://www1.cs.columbia.edu/~db2501/ssmtplib.py</a>)</p> <p>As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.</p> <p>=======================================</p> <pre><code>#! /usr/local/bin/python SMTPserver = 'smtp.att.yahoo.com' sender = 'me@my_email_domain.net' destination = ['recipient@her_email_domain.com'] USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER" PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER" # typical values for text_subtype are plain, html, xml text_subtype = 'plain' content="""\ Test message """ subject="Sent from Python" import sys import os import re from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL) # from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption) # old version # from email.MIMEText import MIMEText from email.mime.text import MIMEText try: msg = MIMEText(content, text_subtype) msg['Subject']= subject msg['From'] = sender # some SMTP servers will do this automatically, not all conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(USERNAME, PASSWORD) try: conn.sendmail(sender, destination, msg.as_string()) finally: conn.quit() except Exception, exc: sys.exit( "mail failed; %s" % str(exc) ) # give a error message </code></pre>
74
2008-09-15T17:24:40Z
[ "python", "smtp" ]
Sending mail from Python using SMTP
64,505
<p>I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?</p> <pre><code>from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "John Doe &lt;[email protected]&gt;" to_addr = "[email protected]" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() </code></pre>
70
2008-09-15T16:36:35Z
275,124
<p>Also if you want to do smtp auth with TLS as opposed to SSL then you just have to change the port (use 587) and do smtp.starttls(). This worked for me:</p> <pre><code>... smtp.connect('YOUR.MAIL.SERVER', 587) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login('USERNAME@DOMAIN', 'PASSWORD') ... </code></pre>
18
2008-11-08T20:12:26Z
[ "python", "smtp" ]
Sending mail from Python using SMTP
64,505
<p>I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?</p> <pre><code>from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "John Doe &lt;[email protected]&gt;" to_addr = "[email protected]" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() </code></pre>
70
2008-09-15T16:36:35Z
11,228,560
<p>What about this? </p> <pre><code>import smtplib SERVER = "localhost" FROM = "[email protected]" TO = ["[email protected]"] # must be a list SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." # Prepare actual message message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) # Send the mail server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit() </code></pre>
4
2012-06-27T14:31:09Z
[ "python", "smtp" ]
Sending mail from Python using SMTP
64,505
<p>I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?</p> <pre><code>from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "John Doe &lt;[email protected]&gt;" to_addr = "[email protected]" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() </code></pre>
70
2008-09-15T16:36:35Z
17,596,848
<p>The method I commonly use...not much different but a little bit</p> <pre><code>import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText msg = MIMEMultipart() msg['From'] = '[email protected]' msg['To'] = '[email protected]' msg['Subject'] = 'simple email in python' message = 'here is the email' msg.attach(MIMEText(message)) mailserver = smtplib.SMTP('smtp.gmail.com',587) # identify ourselves to smtp gmail client mailserver.ehlo() # secure our email with tls encryption mailserver.starttls() # re-identify ourselves as an encrypted connection mailserver.ehlo() mailserver.login('[email protected]', 'mypassword') mailserver.sendmail('[email protected]','[email protected]',msg.as_string()) mailserver.quit() </code></pre> <p>That's it</p>
38
2013-07-11T14:59:54Z
[ "python", "smtp" ]
Sending mail from Python using SMTP
64,505
<p>I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?</p> <pre><code>from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "John Doe &lt;[email protected]&gt;" to_addr = "[email protected]" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() </code></pre>
70
2008-09-15T16:36:35Z
26,191,922
<p>following code is working fine for me:</p> <pre><code>import smtplib to = '[email protected]' gmail_user = '[email protected]' gmail_pwd = 'yourpassword' smtpserver = smtplib.SMTP("smtp.gmail.com",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo() # extra characters to permit edit smtpserver.login(gmail_user, gmail_pwd) header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n' print header msg = header + '\n this is test msg from mkyong.com \n\n' smtpserver.sendmail(gmail_user, to, msg) print 'done!' smtpserver.quit() </code></pre> <p>Ref: <a href="http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/" rel="nofollow">http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/</a></p>
2
2014-10-04T10:31:05Z
[ "python", "smtp" ]
Sending mail from Python using SMTP
64,505
<p>I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?</p> <pre><code>from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "John Doe &lt;[email protected]&gt;" to_addr = "[email protected]" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() </code></pre>
70
2008-09-15T16:36:35Z
29,720,511
<p>See all those lenghty answers? Please allow me to self promote by doing it all in a couple of lines.</p> <p>Import and Connect:</p> <pre><code>import yagmail yag = yagmail.SMTP('[email protected]', host = 'YOUR.MAIL.SERVER', port = 26) </code></pre> <p>Then it is just a one-liner:</p> <pre><code>yag.send('[email protected]', 'hello', 'Hello\nThis is a mail from your server\n\nBye\n') </code></pre> <p>It will actually close when it goes out of scope (or can be closed manually). Furthermore, it will allow you to register your username in your keyring such that you do not have to write out your password in your script (it really bothered me prior to writing <code>yagmail</code>!)</p> <p>For the package/installation, tips and tricks please look at <a href="https://github.com/kootenpv/yagmail" rel="nofollow">git</a> or <a href="https://pypi.python.org/pypi/yagmail/" rel="nofollow">pip</a>, available for both Python 2 and 3.</p>
1
2015-04-18T17:27:00Z
[ "python", "smtp" ]
How to setup VIM autoindentation properly for editing Python files - *.py
65,076
<p>I've troubles setting VIM (7.1.xxx) for editing python files. Indenting seems to be broken (optimal 4 spaces). I've followed some tutorials I found via Google. Still no effect :/ Please help.</p>
47
2008-09-15T17:48:22Z
65,122
<p>I use this on my macbook:</p> <pre><code>" configure expanding of tabs for various file types au BufRead,BufNewFile *.py set expandtab au BufRead,BufNewFile *.c set noexpandtab au BufRead,BufNewFile *.h set noexpandtab au BufRead,BufNewFile Makefile* set noexpandtab " -------------------------------------------------------------------------------- " configure editor with tabs and nice stuff... " -------------------------------------------------------------------------------- set expandtab " enter spaces when tab is pressed set textwidth=120 " break lines when line length increases set tabstop=4 " use 4 spaces to represent tab set softtabstop=4 set shiftwidth=4 " number of spaces to use for auto indent set autoindent " copy indent from current line when starting a new line " make backspaces more powerfull set backspace=indent,eol,start set ruler " show line and column number syntax on " syntax highlighting set showcmd " show (partial) command in status line </code></pre> <p>(edited to only show stuff related to indent / tabs)</p>
42
2008-09-15T17:53:33Z
[ "python", "vim", "configuration", "spaces" ]
How to setup VIM autoindentation properly for editing Python files - *.py
65,076
<p>I've troubles setting VIM (7.1.xxx) for editing python files. Indenting seems to be broken (optimal 4 spaces). I've followed some tutorials I found via Google. Still no effect :/ Please help.</p>
47
2008-09-15T17:48:22Z
66,818
<p>Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.</p> <p>In vim type</p> <p><code>:help vimrc</code></p> <p>and check your path to the _vimrc/.vimrc file with</p> <p><code>:echo $HOME</code></p> <p><code>:echo $VIM</code></p> <p>Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.</p> <p><code>:help source</code></p>
2
2008-09-15T20:50:36Z
[ "python", "vim", "configuration", "spaces" ]
How to setup VIM autoindentation properly for editing Python files - *.py
65,076
<p>I've troubles setting VIM (7.1.xxx) for editing python files. Indenting seems to be broken (optimal 4 spaces). I've followed some tutorials I found via Google. Still no effect :/ Please help.</p>
47
2008-09-15T17:48:22Z
68,002
<p>for more advanced python editing consider installing the <a href="http://eigenclass.org/hiki/simplefold" rel="nofollow">simplefold</a> vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.</p>
0
2008-09-15T23:42:29Z
[ "python", "vim", "configuration", "spaces" ]
How to setup VIM autoindentation properly for editing Python files - *.py
65,076
<p>I've troubles setting VIM (7.1.xxx) for editing python files. Indenting seems to be broken (optimal 4 spaces). I've followed some tutorials I found via Google. Still no effect :/ Please help.</p>
47
2008-09-15T17:48:22Z
1,868,984
<p>I use the vimrc in the python repo among other things:</p> <p><a href="http://svn.python.org/projects/python/trunk/Misc/Vim/vimrc" rel="nofollow">http://svn.python.org/projects/python/trunk/Misc/Vim/vimrc</a></p> <p>I also add</p> <pre><code>set softtabstop=4 </code></pre> <p><a href="http://github.com/skyl/vim-config-python-ide" rel="nofollow">I have my old config here that I'm updating</a></p>
3
2009-12-08T18:37:41Z
[ "python", "vim", "configuration", "spaces" ]
How to setup VIM autoindentation properly for editing Python files - *.py
65,076
<p>I've troubles setting VIM (7.1.xxx) for editing python files. Indenting seems to be broken (optimal 4 spaces). I've followed some tutorials I found via Google. Still no effect :/ Please help.</p>
47
2008-09-15T17:48:22Z
11,830,841
<p>I use:</p> <pre><code>$ cat ~/.vimrc syntax on set showmatch set ts=4 set sts=4 set sw=4 set autoindent set smartindent set smarttab set expandtab set number </code></pre> <p>But but I'm going to try Daren's entries</p>
6
2012-08-06T15:01:33Z
[ "python", "vim", "configuration", "spaces" ]
Caching compiled regex objects in Python?
65,266
<p>Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory.</p> <pre><code>a = re.compile("a.*b") b = re.compile("c.*d") ... </code></pre> <p>Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?</p> <p>Pickling the object simply does the following, causing compilation to happen anyway:</p> <pre><code>&gt;&gt;&gt; import pickle &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; pickle.dumps(x) "cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n." </code></pre> <p>And re objects are unmarshallable:</p> <pre><code>&gt;&gt;&gt; import marshal &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; marshal.dumps(x) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: unmarshallable object </code></pre>
17
2008-09-15T18:10:35Z
65,333
<p>Note that each module initializes itself only once during the life of an app, no matter how many times you import it. So if you compile your expressions at the module's global scope (ie. not in a function) you should be fine.</p>
2
2008-09-15T18:16:24Z
[ "python", "regex", "caching" ]
Caching compiled regex objects in Python?
65,266
<p>Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory.</p> <pre><code>a = re.compile("a.*b") b = re.compile("c.*d") ... </code></pre> <p>Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?</p> <p>Pickling the object simply does the following, causing compilation to happen anyway:</p> <pre><code>&gt;&gt;&gt; import pickle &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; pickle.dumps(x) "cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n." </code></pre> <p>And re objects are unmarshallable:</p> <pre><code>&gt;&gt;&gt; import marshal &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; marshal.dumps(x) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: unmarshallable object </code></pre>
17
2008-09-15T18:10:35Z
65,440
<blockquote> <p>Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?</p> </blockquote> <p>Not easily. You'd have to write a custom serializer that hooks into the C <code>sre</code> implementation of the Python regex engine. Any performance benefits would be vastly outweighed by the time and effort required.</p> <p>First, have you actually profiled the code? I doubt that compiling regexes is a significant part of the application's run-time. Remember that they are only compiled the first time the module is imported in the current execution -- thereafter, the module and its attributes are cached in memory.</p> <p>If you have a program that basically spawns once, compiles a bunch of regexes, and then exits, you could try re-engineering it to perform multiple tests in one invocation. Then you could re-use the regexes, as above.</p> <p>Finally, you could compile the regexes into C-based state machines and then link them in with an extension module. While this would likely be more difficult to maintain, it would eliminate regex compilation entirely from your application.</p>
12
2008-09-15T18:29:51Z
[ "python", "regex", "caching" ]
Caching compiled regex objects in Python?
65,266
<p>Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory.</p> <pre><code>a = re.compile("a.*b") b = re.compile("c.*d") ... </code></pre> <p>Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?</p> <p>Pickling the object simply does the following, causing compilation to happen anyway:</p> <pre><code>&gt;&gt;&gt; import pickle &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; pickle.dumps(x) "cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n." </code></pre> <p>And re objects are unmarshallable:</p> <pre><code>&gt;&gt;&gt; import marshal &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; marshal.dumps(x) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: unmarshallable object </code></pre>
17
2008-09-15T18:10:35Z
65,579
<p>It's possible to place each regex (or group of regexs) into a separate file and then dynamically import the file that you need using the imp module. I doubt that it scales very well but it could be what you need.</p>
-1
2008-09-15T18:45:37Z
[ "python", "regex", "caching" ]
Caching compiled regex objects in Python?
65,266
<p>Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory.</p> <pre><code>a = re.compile("a.*b") b = re.compile("c.*d") ... </code></pre> <p>Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?</p> <p>Pickling the object simply does the following, causing compilation to happen anyway:</p> <pre><code>&gt;&gt;&gt; import pickle &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; pickle.dumps(x) "cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n." </code></pre> <p>And re objects are unmarshallable:</p> <pre><code>&gt;&gt;&gt; import marshal &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; marshal.dumps(x) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: unmarshallable object </code></pre>
17
2008-09-15T18:10:35Z
65,844
<p>The <a href="http://docs.python.org/lib/module-shelve.html" rel="nofollow">shelve</a> module appears to work just fine:</p> <pre><code> import re import shelve a_pattern = "a.*b" b_pattern = "c.*d" a = re.compile(a_pattern) b = re.compile(b_pattern) x = shelve.open('re_cache') x[a_pattern] = a x[b_pattern] = b x.close() # ... x = shelve.open('re_cache') a = x[a_pattern] b = x[b_pattern] x.close() </code></pre> <p>You can then make a nice wrapper class that automatically handles the caching for you so that it becomes transparent to the user... an exercise left to the reader.</p>
0
2008-09-15T19:14:24Z
[ "python", "regex", "caching" ]
Caching compiled regex objects in Python?
65,266
<p>Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory.</p> <pre><code>a = re.compile("a.*b") b = re.compile("c.*d") ... </code></pre> <p>Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?</p> <p>Pickling the object simply does the following, causing compilation to happen anyway:</p> <pre><code>&gt;&gt;&gt; import pickle &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; pickle.dumps(x) "cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n." </code></pre> <p>And re objects are unmarshallable:</p> <pre><code>&gt;&gt;&gt; import marshal &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; marshal.dumps(x) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: unmarshallable object </code></pre>
17
2008-09-15T18:10:35Z
66,666
<p>Hum,</p> <p>Doesn't shelve use pickle ?</p> <p>Anyway, I agree with the previous anwsers. Since a module is processed only once, I doubt compiling regexps will be your app bottle neck. And Python re module is wicked fast since it's coded in C :-)</p> <p>But the good news is that Python got a nice community, so I am sure you can find somebody currently hacking just what you need.</p> <p>I googled 5 sec and found : <a href="http://home.gna.org/oomadness/en/cerealizer/index.html" rel="nofollow">http://home.gna.org/oomadness/en/cerealizer/index.html</a>.</p> <p>Don't know if it will do it but if not, good luck in you research :-)</p>
-1
2008-09-15T20:34:12Z
[ "python", "regex", "caching" ]
Caching compiled regex objects in Python?
65,266
<p>Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory.</p> <pre><code>a = re.compile("a.*b") b = re.compile("c.*d") ... </code></pre> <p>Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?</p> <p>Pickling the object simply does the following, causing compilation to happen anyway:</p> <pre><code>&gt;&gt;&gt; import pickle &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; pickle.dumps(x) "cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n." </code></pre> <p>And re objects are unmarshallable:</p> <pre><code>&gt;&gt;&gt; import marshal &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; marshal.dumps(x) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: unmarshallable object </code></pre>
17
2008-09-15T18:10:35Z
66,846
<p>Open /usr/lib/python2.5/re.py and look for "def _compile". You'll find re.py's internal cache mechanism. </p>
0
2008-09-15T20:53:14Z
[ "python", "regex", "caching" ]
Caching compiled regex objects in Python?
65,266
<p>Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory.</p> <pre><code>a = re.compile("a.*b") b = re.compile("c.*d") ... </code></pre> <p>Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?</p> <p>Pickling the object simply does the following, causing compilation to happen anyway:</p> <pre><code>&gt;&gt;&gt; import pickle &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; pickle.dumps(x) "cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n." </code></pre> <p>And re objects are unmarshallable:</p> <pre><code>&gt;&gt;&gt; import marshal &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; marshal.dumps(x) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: unmarshallable object </code></pre>
17
2008-09-15T18:10:35Z
396,148
<p>First of all, this is a clear limitation in the python re module. It causes a limit how much and how big regular expressions are reasonable. The limit is bigger with long running processes and smaller with short lived processes like command line applications.</p> <p>Some years ago I did look at it and it is possible to dig out the compilation result, pickle it and then unpickle it and reuse it. The problem is that it requires using the sre.py internals and so won't probably work in different python versions.</p> <p>I would like to have this kind of feature in my toolbox. I would also like to know, if there are any separate modules that could be used instead.</p>
1
2008-12-28T13:02:56Z
[ "python", "regex", "caching" ]
How to add method using metaclass
65,400
<p>How do I add an instance method to a class using a metaclass (yes I do need to use a metaclass)? The following kind of works, but the func_name will still be "foo":</p> <pre><code>def bar(self): print "bar" class MetaFoo(type): def __new__(cls, name, bases, dict): dict["foobar"] = bar return type(name, bases, dict) class Foo(object): __metaclass__ = MetaFoo &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; f.foobar() bar &gt;&gt;&gt; f.foobar.func_name 'bar' </code></pre> <p>My problem is that some library code actually uses the func_name and later fails to find the 'bar' method of the Foo instance. I could do:</p> <pre><code>dict["foobar"] = types.FunctionType(bar.func_code, {}, "foobar") </code></pre> <p>There is also types.MethodType, but I need an instance that does'nt exist yet to use that. Am I missing someting here?</p>
5
2008-09-15T18:24:14Z
65,682
<p>I think what you want to do is this:</p> <pre><code>&gt;&gt;&gt; class Foo(): ... def __init__(self, x): ... self.x = x ... &gt;&gt;&gt; def bar(self): ... print 'bar:', self.x ... &gt;&gt;&gt; bar.func_name = 'foobar' &gt;&gt;&gt; Foo.foobar = bar &gt;&gt;&gt; f = Foo(12) &gt;&gt;&gt; f.foobar() bar: 12 &gt;&gt;&gt; f.foobar.func_name 'foobar' </code></pre> <p>Now you are free to pass <code>Foo</code>s to a library that expects <code>Foo</code> instances to have a method named <code>foobar</code>.</p> <p>Unfortunately, (1) I don't know how to use metaclasses and (2) I'm not sure I read your question correctly, but I hope this helps. </p> <p>Note that <code>func_name</code> is only assignable in Python 2.4 and higher.</p>
2
2008-09-15T18:57:29Z
[ "python", "metaclass" ]
How to add method using metaclass
65,400
<p>How do I add an instance method to a class using a metaclass (yes I do need to use a metaclass)? The following kind of works, but the func_name will still be "foo":</p> <pre><code>def bar(self): print "bar" class MetaFoo(type): def __new__(cls, name, bases, dict): dict["foobar"] = bar return type(name, bases, dict) class Foo(object): __metaclass__ = MetaFoo &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; f.foobar() bar &gt;&gt;&gt; f.foobar.func_name 'bar' </code></pre> <p>My problem is that some library code actually uses the func_name and later fails to find the 'bar' method of the Foo instance. I could do:</p> <pre><code>dict["foobar"] = types.FunctionType(bar.func_code, {}, "foobar") </code></pre> <p>There is also types.MethodType, but I need an instance that does'nt exist yet to use that. Am I missing someting here?</p>
5
2008-09-15T18:24:14Z
65,716
<p>Try dynamically extending the bases that way you can take advantage of the mro and the methods are actual methods:</p> <pre><code>class Parent(object): def bar(self): print "bar" class MetaFoo(type): def __new__(cls, name, bases, dict): return type(name, (Parent,) + bases, dict) class Foo(object): __metaclass__ = MetaFoo if __name__ == "__main__": f = Foo() f.bar() print f.bar.func_name </code></pre>
10
2008-09-15T19:01:27Z
[ "python", "metaclass" ]
Decorating a parent class method
66,636
<p>I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but <strong>not</strong> in the parent class.</p> <p>Essentially, I am trying to accomplish the following:</p> <pre><code>class foo(Object): def meth1(self, val): self.value = val class bar(foo): meth1 = classmethod(foo.meth1) </code></pre>
1
2008-09-15T20:31:33Z
66,670
<p>What are you trying to accomplish? If I saw such a construct in live Python code, I would consider beating the original programmer.</p>
3
2008-09-15T20:34:53Z
[ "python", "oop", "inheritance" ]
Decorating a parent class method
66,636
<p>I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but <strong>not</strong> in the parent class.</p> <p>Essentially, I am trying to accomplish the following:</p> <pre><code>class foo(Object): def meth1(self, val): self.value = val class bar(foo): meth1 = classmethod(foo.meth1) </code></pre>
1
2008-09-15T20:31:33Z
66,847
<p>I'm also not entirely sure what the exact behaviour you want is, but assuming its that you want bar.meth1(42) to be equivalent to foo.meth1 being a classmethod of bar (with "self" being the class), then you can acheive this with:</p> <pre><code>def convert_to_classmethod(method): return classmethod(method.im_func) class bar(foo): meth1 = convert_to_classmethod(foo.meth1) </code></pre> <p>The problem with classmethod(foo.meth1) is that foo.meth1 has already been converted to a method, with a special meaning for the first parameter. You need to undo this and look at the underlying function object, reinterpreting what "self" means.</p> <p>I'd also caution that this is a pretty odd thing to do, and thus liable to cause confusion to anyone reading your code. You are probably better off thinking through a different solution to your problem.</p>
3
2008-09-15T20:53:20Z
[ "python", "oop", "inheritance" ]
Decorating a parent class method
66,636
<p>I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but <strong>not</strong> in the parent class.</p> <p>Essentially, I am trying to accomplish the following:</p> <pre><code>class foo(Object): def meth1(self, val): self.value = val class bar(foo): meth1 = classmethod(foo.meth1) </code></pre>
1
2008-09-15T20:31:33Z
66,936
<p>The question, as posed, seems quite odd to me: I can't see why anyone would want to do that. It is possible that you are misunderstanding just what a "classmethod" is in Python (it's a bit different from, say, a static method in Java).</p> <p>A normal method is more-or-less just a function which takes as its first argument (usually called "self"), an instance of the class, and which is invoked as ".".</p> <p>A classmethod is more-or-less just a function which takes as its first argument (often called "cls"), a class, and which can be invoked as "." OR as ".".</p> <p>With this in mind, and your code shown above, what would you expect to have happen if someone creates an instance of bar and calls meth1 on it?</p> <pre><code>bar1 = bar() bar1.meth1("xyz") </code></pre> <p>When the code to meth1 is called, it is passed two arguments 'self' and 'val'. I guess that you expect "xyz" to be passed for 'val', but what are you thinking gets passed for 'self'? Should it be the bar1 instance (in this case, no override was needed)? Or should it be the class bar (what then would this code DO)?</p>
0
2008-09-15T21:02:08Z
[ "python", "oop", "inheritance" ]
How do I create a new signal in pygtk
66,730
<p>I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.</p>
6
2008-09-15T20:41:58Z
66,883
<p>Here is how:</p> <pre><code>import gobject class MyGObjectClass(gobject.GObject): ... gobject.signal_new("signal-name", MyGObjectClass, gobject.SIGNAL_RUN_FIRST, None, (str, int)) </code></pre> <p>Where the second to last argument is the return type and the last argument is a tuple of argument types.</p>
4
2008-09-15T20:57:10Z
[ "python", "gtk", "pygtk", "gobject" ]
How do I create a new signal in pygtk
66,730
<p>I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.</p>
6
2008-09-15T20:41:58Z
67,743
<p>You can also define signals inside the class definition:</p> <pre><code>class MyGObjectClass(gobject.GObject): __gsignals__ = { "some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), } </code></pre> <p>The contents of the tuple are the the same as the three last arguments to <code>gobject.signal_new</code>.</p>
10
2008-09-15T22:52:27Z
[ "python", "gtk", "pygtk", "gobject" ]
How do I create a new signal in pygtk
66,730
<p>I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.</p>
6
2008-09-15T20:41:58Z
126,355
<p>If you use kiwi available <a href="http://kiwi.async.com.br/" rel="nofollow">here</a> you can just do:</p> <pre><code>from kiwi.utils import gsignal class MyObject(gobject.GObject): gsignal('signal-name') </code></pre>
2
2008-09-24T10:14:06Z
[ "python", "gtk", "pygtk", "gobject" ]
mod_python/MySQL error on INSERT with a lot of data: "OperationalError: (2006, 'MySQL server has gone away')"
67,180
<p>When doing an INSERT with a lot of data, ie:</p> <pre><code>INSERT INTO table (mediumtext_field) VALUES ('...lots of text here: about 2MB worth...') </code></pre> <p>MySQL returns </p> <blockquote> <p>"OperationalError: (2006, 'MySQL server has gone away')"</p> </blockquote> <p>This is happening within a minute of starting the script, so it is not a timeout issue. Also, <code>mediumtext_field</code> should be able to hold ~16MB of data, so that shouldn't be a problem.</p> <p>Any ideas what is causing the error or how to work around it?</p> <p>Some relevant libraries being used: <code>mod_python 3.3.1</code>, <code>MySQL 5.0.51</code> (on Windows XP SP3, via xampp, details below)</p> <p><strong>ApacheFriends XAMPP (basic package) version 1.6.5</strong></p> <ul> <li>Apache 2.2.6</li> <li>MySQL 5.0.51</li> <li>phpMyAdmin 2.11.3</li> </ul>
0
2008-09-15T21:29:26Z
72,987
<p>check the max_packet setting in your my.cnf file. this determines the largest amount of data you can send to your mysql server in a single statement. exceeding this values results in that error.</p>
1
2008-09-16T14:34:30Z
[ "python", "mysql", "xampp", "mysql-error-2006" ]
why might my pyglet vertex lists and batches be very slow on Windows?
67,223
<p>I'm writing opengl code in python using the library pyglet. When I draw to the screen using pyglet.graphics.vertex_list or pyglet.graphics.batch objects, they are very slow (~0.1 fps) compared to plain old pyglet.graphics.draw() or just glVertex() calls, which are about 40fps for the same geometry. In Linux the vertex_list is about the same speed as glVertex, which is disappointing, and batch methods are about twice as fast, which is a little better but not as much gain as I was hoping for.</p>
1
2008-09-15T21:33:41Z
67,921
<p>I don't know personally, but I noticed that you haven't posted to <a href="http://groups.google.com/group/pyglet-users" rel="nofollow">the pyglet mailing list</a> about this. More Pyglet users, as well as the primary developer, read that list.</p>
1
2008-09-15T23:24:55Z
[ "python", "opengl", "pyglet" ]
why might my pyglet vertex lists and batches be very slow on Windows?
67,223
<p>I'm writing opengl code in python using the library pyglet. When I draw to the screen using pyglet.graphics.vertex_list or pyglet.graphics.batch objects, they are very slow (~0.1 fps) compared to plain old pyglet.graphics.draw() or just glVertex() calls, which are about 40fps for the same geometry. In Linux the vertex_list is about the same speed as glVertex, which is disappointing, and batch methods are about twice as fast, which is a little better but not as much gain as I was hoping for.</p>
1
2008-09-15T21:33:41Z
835,601
<p>Don't forget to invoke your pyglet scripts with 'python -O myscript.py', the '-O' flag can make a huge performance difference.</p>
4
2009-05-07T16:09:19Z
[ "python", "opengl", "pyglet" ]
Serving dynamically generated ZIP archives in Django
67,454
<p>How to serve users a dynamically generated ZIP archive in Django?</p> <p>I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.</p>
41
2008-09-15T22:00:31Z
67,477
<p>Can't you just write a link to a "zip server" or whatnot? Why does the zip archive itself need to be served from Django? A 90's era CGI script to generate a zip and spit it to stdout is really all that's required here, at least as far as I can see.</p>
1
2008-09-15T22:03:03Z
[ "python", "django" ]
Serving dynamically generated ZIP archives in Django
67,454
<p>How to serve users a dynamically generated ZIP archive in Django?</p> <p>I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.</p>
41
2008-09-15T22:00:31Z
67,527
<p>Django doesn't directly handle the generation of dynamic content (specifically Zip files). That work would be done by Python's standard library. You can take a look at how to dynamically create a Zip file in Python <a href="https://docs.python.org/2/library/zipfile.html#zipfile-objects" rel="nofollow">here</a>.</p> <p>If you're worried about it slowing down your server you can cache the requests if you expect to have many of the same requests. You can use Django's <a href="http://docs.djangoproject.com/en/dev/topics/cache/#topics-cache" rel="nofollow">cache framework</a> to help you with that.</p> <p>Overall, zipping files can be CPU intensive but Django shouldn't be any slower than another Python web framework.</p>
6
2008-09-15T22:09:50Z
[ "python", "django" ]
Serving dynamically generated ZIP archives in Django
67,454
<p>How to serve users a dynamically generated ZIP archive in Django?</p> <p>I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.</p>
41
2008-09-15T22:00:31Z
72,180
<p>The solution is as follows.</p> <p>Use Python module <a href="http://docs.python.org/lib/module-zipfile.html">zipfile</a> to create zip archive, but as the file specify <a href="http://docs.python.org/lib/module-StringIO.html">StringIO</a> object (ZipFile constructor requires file-like object). Add files you want to compress. Then in your Django application return the content of StringIO object in <code>HttpResponse</code> with mimetype set to <code>application/x-zip-compressed</code> (or at least <code>application/octet-stream</code>). If you want, you can set <code>content-disposition</code> header, but this should not be really required.</p> <p>But beware, creating zip archives on each request is bad idea and this may kill your server (not counting timeouts if the archives are large). Performance-wise approach is to cache generated output somewhere in filesystem and regenerate it only if source files have changed. Even better idea is to prepare archives in advance (eg. by cron job) and have your web server serving them as usual statics.</p>
36
2008-09-16T13:30:56Z
[ "python", "django" ]
Serving dynamically generated ZIP archives in Django
67,454
<p>How to serve users a dynamically generated ZIP archive in Django?</p> <p>I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.</p>
41
2008-09-15T22:00:31Z
73,617
<p>I suggest to use separate model for storing those temp zip files. You can create zip on-fly, save to model with filefield and finally send url to user.</p> <p>Advantages:</p> <ul> <li>Serving static zip files with django media mechanism (like usual uploads).</li> <li>Ability to cleanup stale zip files by regular cron script execution (which can use date field from zip file model).</li> </ul>
1
2008-09-16T15:31:39Z
[ "python", "django" ]
Serving dynamically generated ZIP archives in Django
67,454
<p>How to serve users a dynamically generated ZIP archive in Django?</p> <p>I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.</p>
41
2008-09-15T22:00:31Z
12,951,461
<p>Here's a Django view to do this:</p> <pre><code>import os import zipfile import StringIO from django.http import HttpResponse def getfiles(request): # Files (local path) to put in the .zip # FIXME: Change this (get paths from DB etc) filenames = ["/tmp/file1.txt", "/tmp/file2.txt"] # Folder name in ZIP archive which contains the above files # E.g [thearchive.zip]/somefiles/file2.txt # FIXME: Set this to something better zip_subdir = "somefiles" zip_filename = "%s.zip" % zip_subdir # Open StringIO to grab in-memory ZIP contents s = StringIO.StringIO() # The zip compressor zf = zipfile.ZipFile(s, "w") for fpath in filenames: # Calculate path for file in zip fdir, fname = os.path.split(fpath) zip_path = os.path.join(zip_subdir, fname) # Add file, at correct path zf.write(fpath, zip_path) # Must close zip for all contents to be written zf.close() # Grab ZIP file from in-memory, make response with correct MIME-type resp = HttpResponse(s.getvalue(), mimetype = "application/x-zip-compressed") # ..and correct content-disposition resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename return resp </code></pre>
29
2012-10-18T09:32:10Z
[ "python", "django" ]
Serving dynamically generated ZIP archives in Django
67,454
<p>How to serve users a dynamically generated ZIP archive in Django?</p> <p>I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.</p>
41
2008-09-15T22:00:31Z
24,178,943
<p>This module generates and streams an archive: <a href="https://github.com/allanlei/python-zipstream" rel="nofollow">https://github.com/allanlei/python-zipstream</a></p> <p>(I'm not connected to the development. Just thinking about using it.)</p>
0
2014-06-12T07:39:32Z
[ "python", "django" ]
Serving dynamically generated ZIP archives in Django
67,454
<p>How to serve users a dynamically generated ZIP archive in Django?</p> <p>I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.</p>
41
2008-09-15T22:00:31Z
26,658,291
<p>Shameless plug: you can use <a href="https://github.com/thibault/django-zipview">django-zipview</a> for the same purpose.</p> <p>After a <code>pip install django-zipview</code>:</p> <pre><code>from zipview.views import BaseZipView from reviews import Review class CommentsArchiveView(BaseZipView): """Download at once all comments for a review.""" def get_files(self): document_key = self.kwargs.get('document_key') reviews = Review.objects \ .filter(document__document_key=document_key) \ .exclude(comments__isnull=True) return [review.comments.file for review in reviews if review.comments.name] </code></pre>
5
2014-10-30T16:24:34Z
[ "python", "django" ]
Serving dynamically generated ZIP archives in Django
67,454
<p>How to serve users a dynamically generated ZIP archive in Django?</p> <p>I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.</p>
41
2008-09-15T22:00:31Z
40,076,866
<p>For python3 i use the <strong>io.ByteIO</strong> since <strong>StringIO</strong> is deprecated to achieve this. Hope it helps.</p> <pre><code>import io def my_downloadable_zip(request): zip_io = io.BytesIO() with zipfile.ZipFile(zip_io, mode='w', compression=zipfile.ZIP_DEFLATED) as backup_zip: backup_zip.write('file_name_loc_to_zip') # u can also make use of list of filename location # and do some iteration over it response = HttpResponse(zip_io.getvalue(), content_type='application/x-zip-compressed') response['Content-Disposition'] = 'attachment; filename=%s' % 'your_zipfilename' + ".zip" response['Content-Length'] = zip_io.tell() return response </code></pre>
0
2016-10-17T00:10:09Z
[ "python", "django" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
67,672
<p>I believe you can use <a href="https://docs.python.org/2/library/imp.html#imp.find_module" rel="nofollow"><code>imp.find_module()</code></a> and <a href="https://docs.python.org/2/library/imp.html#imp.load_module" rel="nofollow"><code>imp.load_module()</code></a> to load the specified module. You'll need to split the module name off of the path, i.e. if you wanted to load <code>/home/mypath/mymodule.py</code> you'd need to do:</p> <pre><code>imp.find_module('mymodule', '/home/mypath/') </code></pre> <p>...but that should get the job done.</p>
3
2008-09-15T22:37:24Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
67,692
<p>For Python 3.5+ use:</p> <pre><code>import importlib.util spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py") foo = importlib.util.module_from_spec(spec) spec.loader.exec_module(foo) foo.MyClass() </code></pre> <p>For Python 3.3 and 3.4 use:</p> <pre><code>from importlib.machinery import SourceFileLoader foo = SourceFileLoader("module.name", "/path/to/file.py").load_module() foo.MyClass() </code></pre> <p>(Although this has been deprecated in Python 3.4.)</p> <p>Python 2 use:</p> <pre><code>import imp foo = imp.load_source('module.name', '/path/to/file.py') foo.MyClass() </code></pre> <p>There are equivalent convenience functions for compiled Python files and DLLs.</p> <p>See also. <a href="http://bugs.python.org/issue21436">http://bugs.python.org/issue21436</a>.</p>
575
2008-09-15T22:41:16Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
67,693
<p>You can use the </p> <pre><code>load_source(module_name, path_to_file) </code></pre> <p>method from <a href="https://docs.python.org/library/imp.html">imp module</a>.</p>
12
2008-09-15T22:41:24Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
67,705
<p><strong>Import package modules at runtime (Python recipe)</strong> </p> <p><a href="http://code.activestate.com/recipes/223972/" rel="nofollow">http://code.activestate.com/recipes/223972/</a></p> <pre><code>################### ## # ## classloader.py # ## # ################### import sys, types def _get_mod(modulePath): try: aMod = sys.modules[modulePath] if not isinstance(aMod, types.ModuleType): raise KeyError except KeyError: # The last [''] is very important! aMod = __import__(modulePath, globals(), locals(), ['']) sys.modules[modulePath] = aMod return aMod def _get_func(fullFuncName): """Retrieve a function object from a full dotted-package name.""" # Parse out the path, module, and function lastDot = fullFuncName.rfind(u".") funcName = fullFuncName[lastDot + 1:] modPath = fullFuncName[:lastDot] aMod = _get_mod(modPath) aFunc = getattr(aMod, funcName) # Assert that the function is a *callable* attribute. assert callable(aFunc), u"%s is not callable." % fullFuncName # Return a reference to the function itself, # not the results of the function. return aFunc def _get_class(fullClassName, parentClass=None): """Load a module and retrieve a class (NOT an instance). If the parentClass is supplied, className must be of parentClass or a subclass of parentClass (or None is returned). """ aClass = _get_func(fullClassName) # Assert that the class is a subclass of parentClass. if parentClass is not None: if not issubclass(aClass, parentClass): raise TypeError(u"%s is not a subclass of %s" % (fullClassName, parentClass)) # Return a reference to the class itself, not an instantiated object. return aClass ###################### ## Usage ## ###################### class StorageManager: pass class StorageManagerMySQL(StorageManager): pass def storage_object(aFullClassName, allOptions={}): aStoreClass = _get_class(aFullClassName, StorageManager) return aStoreClass(allOptions) </code></pre>
2
2008-09-15T22:43:20Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
67,708
<p>You can also do something like this and add the directory that the configuration file is sitting in to the Python load path, and then just do a normal import, assuming you know the name of the file in advance, in this case "config".</p> <p>Messy, but it works.</p> <pre><code>configfile = '~/config.py' import os import sys sys.path.append(os.path.dirname(os.path.expanduser(configfile))) import config </code></pre>
13
2008-09-15T22:44:50Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
67,715
<p>Do you mean load or import?</p> <p>You can manipulate the sys.path list specify the path to your module, then import your module. For example, given a module at:</p> <pre><code>/foo/bar.py </code></pre> <p>You could do:</p> <pre><code>import sys sys.path[0:0] = '/foo' # puts the /foo directory at the start of your path import bar </code></pre>
8
2008-09-15T22:46:35Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
68,628
<pre><code>def import_file(full_path_to_module): try: import os module_dir, module_file = os.path.split(full_path_to_module) module_name, module_ext = os.path.splitext(module_file) save_cwd = os.getcwd() os.chdir(module_dir) module_obj = __import__(module_name) module_obj.__file__ = full_path_to_module globals()[module_name] = module_obj os.chdir(save_cwd) except: raise ImportError import_file('/home/somebody/somemodule.py') </code></pre>
9
2008-09-16T01:43:04Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
129,374
<p>The advantage of adding a path to sys.path (over using imp) is that it simplifies things when importing more than one module from a single package. For example:</p> <pre><code>import sys # the mock-0.3.1 dir contains testcase.py, testutils.py &amp; mock.py sys.path.append('/foo/bar/mock-0.3.1') from testcase import TestCase from testutils import RunTests from mock import Mock, sentinel, patch </code></pre>
185
2008-09-24T19:36:16Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
6,284,270
<p>I made a package that uses <code>imp</code> for you. I call it <code>import_file</code> and this is how it's used:</p> <pre><code>&gt;&gt;&gt;from import_file import import_file &gt;&gt;&gt;mylib = import_file('c:\\mylib.py') &gt;&gt;&gt;another = import_file('relative_subdir/another.py') </code></pre> <p>You can get it at:</p> <p><a href="http://pypi.python.org/pypi/import_file" rel="nofollow">http://pypi.python.org/pypi/import_file</a></p> <p>or at</p> <p><a href="http://code.google.com/p/import-file/" rel="nofollow">http://code.google.com/p/import-file/</a></p>
1
2011-06-08T19:41:29Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
8,721,254
<p>This should work</p> <pre><code>path = os.path.join('./path/to/folder/with/py/files', '*.py') for infile in glob.glob(path): basename = os.path.basename(infile) basename_without_extension = basename[:-3] # http://docs.python.org/library/imp.html?highlight=imp#module-imp imp.load_source(basename_without_extension, infile) </code></pre>
3
2012-01-04T02:17:21Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
25,827,116
<p>You can use the <code>pkgutil</code> module (specifically the <a href="https://docs.python.org/3/library/pkgutil.html#pkgutil.walk_packages" rel="nofollow"><code>walk_packages</code></a> method) to get a list of the packages in the current directory. From there it's trivial to use the <code>importlib</code> machinery to import the modules you want:</p> <pre><code>import pkgutil import importlib packages = pkgutil.walk_packages(path='.') for importer, name, is_package in packages: mod = importlib.import_module(name) # do whatever you want with module now, it's been imported! </code></pre>
2
2014-09-13T19:57:28Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
26,995,106
<p>In Linux, adding a symbolic link in the directory your python script is located works.</p> <p>ie: </p> <p>ln -s /absolute/path/to/module/module.py /absolute/path/to/script/module.py</p> <p>python will create /absolute/path/to/script/module.pyc and will update it if you change the contents of /absolute/path/to/module/module.py</p> <p>then include the following in mypythonscript.py</p> <p>from module import *</p>
1
2014-11-18T13:06:35Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
27,127,448
<p>The best way, I think, is from the official documentation (<a href="https://docs.python.org/3.2/library/imp.html#examples" rel="nofollow">29.1. imp — Access the import internals</a>):</p> <pre><code>import imp import sys def __import__(name, globals=None, locals=None, fromlist=None): # Fast path: see if the module has already been imported. try: return sys.modules[name] except KeyError: pass # If any of the following calls raises an exception, # there's a problem we can't handle -- let the caller handle it. fp, pathname, description = imp.find_module(name) try: return imp.load_module(name, fp, pathname, description) finally: # Since we may exit via an exception, close fp explicitly. if fp: fp.close() </code></pre>
0
2014-11-25T12:58:47Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
29,589,414
<p>This area of Python 3.4 seems to be extremely tortuous to understand! However with a bit of hacking using the code from Chris Calloway as a start I managed to get something working. Here's the basic function.</p> <pre><code>def import_module_from_file(full_path_to_module): """ Import a module given the full path/filename of the .py file Python 3.4 """ module = None try: # Get module name and path from full path module_dir, module_file = os.path.split(full_path_to_module) module_name, module_ext = os.path.splitext(module_file) # Get module "spec" from filename spec = importlib.util.spec_from_file_location(module_name,full_path_to_module) module = spec.loader.load_module() except Exception as ec: # Simple error printing # Insert "sophisticated" stuff here print(ec) finally: return module </code></pre> <p>This appears to use non-deprecated modules from Python 3.4. I don't pretend to understand why, but it seems to work from within a program. I found Chris' solution worked on the command line but not from inside a program.</p>
1
2015-04-12T12:22:56Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
30,605,451
<p>I'm not saying that it is better, but for the sake of completeness, I wanted to suggest the <a href="https://docs.python.org/3/library/functions.html#exec" rel="nofollow"><code>exec</code></a> function, available in both python 2 and 3. <code>exec</code> allows you to execute arbitrary code in either the global scope, or in an internal scope, provided as a dictionary.</p> <p>For example, if you have a module stored in <code>"/path/to/module</code>" with the function <code>foo()</code>, you could run it by doing the following:</p> <pre><code>module = dict() with open("/path/to/module") as f: exec(f.read(), module) module['foo']() </code></pre> <p>This makes it a bit more explicit that you're loading code dynamically, and grants you some additional power, such as the ability to provide custom builtins. </p> <p>And if having access through attributes, instead of keys is important to you, you can design a custom dict class for the globals, that provides such access, e.g.:</p> <pre><code>class MyModuleClass(dict): def __getattr__(self, name): return self.__getitem__(name) </code></pre>
2
2015-06-02T19:57:46Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
32,905,959
<p>To import a module from a given filename, you can temporarily extend the path, and restore the system path in the finally block <a href="http://effbot.org/zone/import-string.htm" rel="nofollow">reference:</a></p> <pre><code>filename = "directory/module.py" directory, module_name = os.path.split(filename) module_name = os.path.splitext(module_name)[0] path = list(sys.path) sys.path.insert(0, directory) try: module = __import__(module_name) finally: sys.path[:] = path # restore </code></pre>
1
2015-10-02T11:14:13Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
34,570,493
<p>It may be obvious but in interactive shell:</p> <pre><code>cd path import module </code></pre>
-1
2016-01-02T20:37:55Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
37,339,817
<p>It sounds like you don't want to specifically import the configuration file (which has a whole lot of side effects and additional complications involved), you just want to run it, and be able to access the resulting namespace. The standard library provides an API specifically for that in the form of <a href="https://docs.python.org/3/library/runpy.html#runpy.run_path" rel="nofollow">runpy.run_path</a>:</p> <pre><code>from runpy import run_path settings = run_path("/path/to/file.py") </code></pre> <p>That interface is available in Python 2.7 and Python 3.2+</p>
1
2016-05-20T06:52:17Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
37,611,448
<p>Here is some code that works in all Python versions, from 2.7-3.5 and probably even others.</p> <pre><code>config_file = "/tmp/config.py" with open(config_file) as f: code = compile(f.read(), config_file, 'exec') exec(code, globals(), locals()) </code></pre> <p>I tested it. It may be ugly but so far is the only one that works in all versions.</p>
1
2016-06-03T10:04:52Z
[ "python", "configuration", "python-import", "python-module" ]
How to import a module given the full path?
67,631
<p>How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.</p>
498
2008-09-15T22:30:55Z
38,076,473
<pre><code>import sys sys.path.append('/your/modul/path') </code></pre>
1
2016-06-28T12:36:18Z
[ "python", "configuration", "python-import", "python-module" ]
Why do you need explicitly have the "self" argument into a Python method?
68,282
<p>When defining a method on a class in Python, it looks something like this:</p> <pre><code>class MyClass(object): def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. </p> <p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p>
125
2008-09-16T00:39:55Z
68,320
<p>It's to minimize the difference between methods and functions. It allows you to easily generate methods in metaclasses, or add methods at runtime to pre-existing classes.</p> <p>e.g.</p> <pre><code>&gt;&gt;&gt; class C(object): ... def foo(self): ... print "Hi!" ... &gt;&gt;&gt; &gt;&gt;&gt; def bar(self): ... print "Bork bork bork!" ... &gt;&gt;&gt; &gt;&gt;&gt; c = C() &gt;&gt;&gt; C.bar = bar &gt;&gt;&gt; c.bar() Bork bork bork! &gt;&gt;&gt; c.foo() Hi! &gt;&gt;&gt; </code></pre> <p>It also (as far as I know) makes the implementation of the python runtime easier.</p>
37
2008-09-16T00:47:18Z
[ "python" ]
Why do you need explicitly have the "self" argument into a Python method?
68,282
<p>When defining a method on a class in Python, it looks something like this:</p> <pre><code>class MyClass(object): def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. </p> <p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p>
125
2008-09-16T00:39:55Z
68,324
<p>I like to quote Peters' Zen of Python. "Explicit is better than implicit."</p> <p>In Java and C++, '<code>this.</code>' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't.</p> <p>Python elects to make things like this explicit rather than based on a rule. </p> <p>Additionally, since nothing is implied or assumed, parts of the implementation are exposed. <code>self.__class__</code>, <code>self.__dict__</code> and other "internal" structures are available in an obvious way.</p>
68
2008-09-16T00:47:55Z
[ "python" ]
Why do you need explicitly have the "self" argument into a Python method?
68,282
<p>When defining a method on a class in Python, it looks something like this:</p> <pre><code>class MyClass(object): def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. </p> <p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p>
125
2008-09-16T00:39:55Z
68,329
<p>There is also another very simple answer: according to the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">zen of python</a>, "explicit is better than implicit".</p>
-1
2008-09-16T00:49:26Z
[ "python" ]
Why do you need explicitly have the "self" argument into a Python method?
68,282
<p>When defining a method on a class in Python, it looks something like this:</p> <pre><code>class MyClass(object): def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. </p> <p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p>
125
2008-09-16T00:39:55Z
68,472
<p>Python doesn't force you on using "self". You can give it whatever name you want. You just have to remember that the first argument in a method definition header is a reference to the object.</p>
10
2008-09-16T01:15:16Z
[ "python" ]
Why do you need explicitly have the "self" argument into a Python method?
68,282
<p>When defining a method on a class in Python, it looks something like this:</p> <pre><code>class MyClass(object): def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. </p> <p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p>
125
2008-09-16T00:39:55Z
308,045
<p>I suggest that one should read <a href="http://neopythonic.blogspot.com/" rel="nofollow">Guido van Rossum's blog</a> on this topic - <a href="http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html" rel="nofollow">Why explicit self has to stay</a>.</p> <blockquote> <p>When a method definition is decorated, we don't know whether to automatically give it a 'self' parameter or not: the decorator could turn the function into a static method (which has no 'self'), or a class method (which has a funny kind of self that refers to a class instead of an instance), or it could do something completely different (it's trivial to write a decorator that implements '@classmethod' or '@staticmethod' in pure Python). There's no way without knowing what the decorator does whether to endow the method being defined with an implicit 'self' argument or not.</p> <p>I reject hacks like special-casing '@classmethod' and '@staticmethod'.</p> </blockquote>
38
2008-11-21T06:28:26Z
[ "python" ]
Why do you need explicitly have the "self" argument into a Python method?
68,282
<p>When defining a method on a class in Python, it looks something like this:</p> <pre><code>class MyClass(object): def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. </p> <p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p>
125
2008-09-16T00:39:55Z
29,369,904
<p>I think it has to do with PEP 227:</p> <blockquote> <p>Names in class scope are not accessible. Names are resolved in the innermost enclosing function scope. If a class definition occurs in a chain of nested scopes, the resolution process skips class definitions. This rule prevents odd interactions between class attributes and local variable access. If a name binding operation occurs in a class definition, it creates an attribute on the resulting class object. To access this variable in a method, or in a function nested within a method, an attribute reference must be used, either via self or via the class name.</p> </blockquote>
1
2015-03-31T13:29:09Z
[ "python" ]
Why do you need explicitly have the "self" argument into a Python method?
68,282
<p>When defining a method on a class in Python, it looks something like this:</p> <pre><code>class MyClass(object): def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. </p> <p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p>
125
2008-09-16T00:39:55Z
31,367,197
<p>Also allows you to do this: (in short, invoking <code>Outer(3).create_inner_class(4)().weird_sum_with_closure_scope(5)</code> will return 12, but will do so in the craziest of ways.</p> <pre><code>class Outer(object): def __init__(self, outer_num): self.outer_num = outer_num def create_inner_class(outer_self, inner_arg): class Inner(object): inner_arg = inner_arg def weird_sum_with_closure_scope(inner_self, num) return num + outer_self.outer_num + inner_arg return Inner </code></pre> <p>Of course, this is harder to imagine in languages like Java and C#. By making the self reference explicit, you're free to refer to any object by that self reference. Also, such a way of playing with classes at runtime is harder to do in the more static languages - not that's it's necessarily good or bad. It's just that the explicit self allows all this craziness to exist.</p> <p>Moreover, imagine this: We'd like to customize the behavior of methods (for profiling, or some crazy black magic). This can lead us to think: what if we had a class <code>Method</code> whose behavior we could override or control?</p> <p>Well here it is:</p> <pre><code>from functools import partial class MagicMethod(object): """Does black magic when called""" def __get__(self, obj, obj_type): # This binds the &lt;other&gt; class instance to the &lt;innocent_self&gt; parameter # of the method MagicMethod.invoke return partial(self.invoke, obj) def invoke(magic_self, innocent_self, *args, **kwargs): # do black magic here ... print magic_self, innocent_self, args, kwargs class InnocentClass(object): magic_method = MagicMethod() </code></pre> <p>And now: <code>InnocentClass().magic_method()</code> will act like expected. The method will be bound with the <code>innocent_self</code> parameter to <code>InnocentClass</code>, and with the <code>magic_self</code> to the MagicMethod instance. Weird huh? It's like having 2 keywords <code>this1</code> and <code>this2</code> in languages like Java and C#. Magic like this allows frameworks to do stuff that would otherwise be much more verbose.</p> <p>Again, I don't want to comment on the ethics of this stuff. I just wanted to show things that would be harder to do without an explicit self reference.</p>
4
2015-07-12T11:18:06Z
[ "python" ]
Why do you need explicitly have the "self" argument into a Python method?
68,282
<p>When defining a method on a class in Python, it looks something like this:</p> <pre><code>class MyClass(object): def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. </p> <p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p>
125
2008-09-16T00:39:55Z
36,968,741
<p>I think the real reason besides "The Zen of Python" is that Functions are first class citizens in Python. </p> <p>Which essentially makes them an Object. Now The fundamental issue is if your functions are object as well then, in Object oriented paradigm how would you send messages to Objects when the messages themselves are objects ? </p> <p>Looks like a chicken egg problem, to reduce this paradox, the only possible way is to either pass a context of execution to methods or detect it. But since python can have nested functions it would be impossible to do so as the context of execution would change for inner functions. </p> <p>This means the only possible solution is to explicitly pass 'self' (The context of execution).</p> <p>So i believe it is a implementation problem the Zen came much later.</p>
0
2016-05-01T16:01:06Z
[ "python" ]
Change command Method for Tkinter Button in Python
68,327
<p>I create a new Button object but did not specify the <code>command</code> option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created?</p>
3
2008-09-16T00:48:37Z
68,455
<p>Sure; just use the <code>bind</code> method to specify the callback after the button has been created. I've just written and tested the example below. You can find a nice tutorial on doing this at <a href="http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm" rel="nofollow">http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm</a></p> <pre><code>from Tkinter import Tk, Button root = Tk() button = Button(root, text="Click Me!") button.pack() def callback(event): print "Hello World!" button.bind("&lt;Button-1&gt;", callback) root.mainloop() </code></pre>
1
2008-09-16T01:12:22Z
[ "python", "user-interface", "tkinter" ]
Change command Method for Tkinter Button in Python
68,327
<p>I create a new Button object but did not specify the <code>command</code> option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created?</p>
3
2008-09-16T00:48:37Z
68,524
<p>Though <a href="http://stackoverflow.com/questions/68327/change-command-method-for-tkinter-button-in-python#68455">Eli Courtwright's</a> program will work fine¹, what you really seem to want though is just a way to reconfigure after instantiation any attribute which you could have set when you instantiated². How you do so is by way of the configure() method.</p> <pre><code>from Tkinter import Tk, Button def goodbye_world(): print "Goodbye World!\nWait, I changed my mind!" button.configure(text = "Hello World!", command=hello_world) def hello_world(): print "Hello World!\nWait, I changed my mind!" button.configure(text = "Goodbye World!", command=goodbye_world) root = Tk() button = Button(root, text="Hello World!", command=hello_world) button.pack() root.mainloop() </code></pre> <p>¹ "fine" if you use only the mouse; if you care about tabbing and using [Space] or [Enter] on buttons, then you will have to implement (duplicating existing code) keypress events too. Setting the <code>command</code> option through <code>.configure</code> is much easier.</p> <p>² the only attribute that can't change after instantiation is <code>name</code>.</p>
12
2008-09-16T01:24:37Z
[ "python", "user-interface", "tkinter" ]
How to copy a file to a remote server in Python using SCP or SSH?
68,335
<p>I have a text file on my local machine that is generated by a daily Python script run in cron. </p> <p>I would like to add a bit of code to have that file sent securely to my server over SSH.</p>
55
2008-09-16T00:50:10Z
68,365
<p>If you want the simple approach, this should work.</p> <p>You'll want to ".close()" the file first so you know it's flushed to disk from Python.</p> <pre><code>import os os.system("scp FILE USER@SERVER:PATH") #e.g. os.system("scp foo.bar [email protected]:/path/to/foo.bar") </code></pre> <p>You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password). </p> <p><a href="http://www.modwest.com/help/kb20-90.html">ssh-keygen example</a></p>
21
2008-09-16T00:55:43Z
[ "python", "ssh", "automation", "scp" ]
How to copy a file to a remote server in Python using SCP or SSH?
68,335
<p>I have a text file on my local machine that is generated by a daily Python script run in cron. </p> <p>I would like to add a bit of code to have that file sent securely to my server over SSH.</p>
55
2008-09-16T00:50:10Z
68,377
<p>Kind of hacky, but the following should work :)</p> <pre><code>import os filePath = "/foo/bar/baz.py" serverPath = "/blah/boo/boom.py" os.system("scp "+filePath+" [email protected]:"+serverPath) </code></pre>
-1
2008-09-16T00:56:31Z
[ "python", "ssh", "automation", "scp" ]
How to copy a file to a remote server in Python using SCP or SSH?
68,335
<p>I have a text file on my local machine that is generated by a daily Python script run in cron. </p> <p>I would like to add a bit of code to have that file sent securely to my server over SSH.</p>
55
2008-09-16T00:50:10Z
68,382
<p>You'd probably use the <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow">subprocess module</a>. Something like this:</p> <pre><code>import subprocess p = subprocess.Popen(["scp", myfile, destination]) sts = os.waitpid(p.pid, 0) </code></pre> <p>Where <code>destination</code> is probably of the form <code>user@remotehost:remotepath</code>. Thanks to @Charles Duffy for pointing out the weakness in my original answer, which used a single string argument to specify the scp operation <code>shell=True</code> - that wouldn't handle whitespace in paths.</p> <p>The module documentation has <a href="http://docs.python.org/lib/node536.html" rel="nofollow">examples of error checking that you may want to perform in conjunction with this operation.</a></p> <p>Ensure that you've set up proper credentials so that you can perform an <a href="http://www.debian.org/devel/passwordlessssh" rel="nofollow">unattended, passwordless scp between the machines</a>. There is a <a href="http://stackoverflow.com/questions/7260/how-do-i-setup-public-key-authentication">stackoverflow question for this already</a>.</p>
23
2008-09-16T00:58:49Z
[ "python", "ssh", "automation", "scp" ]
How to copy a file to a remote server in Python using SCP or SSH?
68,335
<p>I have a text file on my local machine that is generated by a daily Python script run in cron. </p> <p>I would like to add a bit of code to have that file sent securely to my server over SSH.</p>
55
2008-09-16T00:50:10Z
68,566
<p>There are a couple of different ways to approach the problem:</p> <ol> <li>Wrap command-line programs</li> <li>use a Python library that provides SSH capabilities (eg - <a href="http://www.lag.net/paramiko/">Paramiko</a> or <a href="http://twistedmatrix.com/trac/wiki/TwistedConch">Twisted Conch</a>)</li> </ol> <p>Each approach has its own quirks. You will need to setup SSH keys to enable password-less logins if you are wrapping system commands like "ssh", "scp" or "rsync." You can embed a password in a script using Paramiko or some other library, but you might find the lack of documentation frustrating, especially if you are not familiar with the basics of the SSH connection (eg - key exchanges, agents, etc). It probably goes without saying that SSH keys are almost always a better idea than passwords for this sort of stuff.</p> <p>NOTE: its hard to beat rsync if you plan on transferring files via SSH, especially if the alternative is plain old scp.</p> <p>I've used Paramiko with an eye towards replacing system calls but found myself drawn back to the wrapped commands due to their ease of use and immediate familiarity. You might be different. I gave Conch the once-over some time ago but it didn't appeal to me.</p> <p>If opting for the system-call path, Python offers an array of options such as os.system or the commands/subprocess modules. I'd go with the subprocess module if using version 2.4+.</p>
10
2008-09-16T01:32:08Z
[ "python", "ssh", "automation", "scp" ]
How to copy a file to a remote server in Python using SCP or SSH?
68,335
<p>I have a text file on my local machine that is generated by a daily Python script run in cron. </p> <p>I would like to add a bit of code to have that file sent securely to my server over SSH.</p>
55
2008-09-16T00:50:10Z
69,596
<p>To do this in Python (i.e. not wrapping scp through subprocess.Popen or similar) with the <a href="http://www.lag.net/paramiko/">Paramiko</a> library, you would do something like this:</p> <pre><code>import os import paramiko ssh = paramiko.SSHClient() ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))) ssh.connect(server, username=username, password=password) sftp = ssh.open_sftp() sftp.put(localpath, remotepath) sftp.close() ssh.close() </code></pre> <p>(You would probably want to deal with unknown hosts, errors, creating any directories necessary, and so on).</p>
76
2008-09-16T05:27:59Z
[ "python", "ssh", "automation", "scp" ]
How to copy a file to a remote server in Python using SCP or SSH?
68,335
<p>I have a text file on my local machine that is generated by a daily Python script run in cron. </p> <p>I would like to add a bit of code to have that file sent securely to my server over SSH.</p>
55
2008-09-16T00:50:10Z
22,710,513
<p><a href="http://fabfile.org" rel="nofollow"><code>fabric</code></a> could be used to upload files vis ssh:</p> <pre><code>#!/usr/bin/env python from fabric.api import execute, put from fabric.network import disconnect_all if __name__=="__main__": import sys # specify hostname to connect to and the remote/local paths srcdir, remote_dirname, hostname = sys.argv[1:] try: s = execute(put, srcdir, remote_dirname, host=hostname) print(repr(s)) finally: disconnect_all() </code></pre>
1
2014-03-28T10:41:18Z
[ "python", "ssh", "automation", "scp" ]
How to copy a file to a remote server in Python using SCP or SSH?
68,335
<p>I have a text file on my local machine that is generated by a daily Python script run in cron. </p> <p>I would like to add a bit of code to have that file sent securely to my server over SSH.</p>
55
2008-09-16T00:50:10Z
22,710,752
<p>Calling <code>scp</code> command via subprocess doesn't allow to receive the progress report inside the script. <code>pexpect</code> could be used to extract that info:</p> <pre><code>import pipes import re import pexpect # $ pip install pexpect def progress(locals): # extract percents print(int(re.search(br'(\d+)%$', locals['child'].after).group(1))) command = "scp %s %s" % tuple(map(pipes.quote, [srcfile, destination])) pexpect.run(command, events={r'\d+%': progress}) </code></pre> <p>See <a href="http://stackoverflow.com/q/22687296/4279">python copy file in local network (linux -> linux)</a></p>
0
2014-03-28T10:50:46Z
[ "python", "ssh", "automation", "scp" ]
How to copy a file to a remote server in Python using SCP or SSH?
68,335
<p>I have a text file on my local machine that is generated by a daily Python script run in cron. </p> <p>I would like to add a bit of code to have that file sent securely to my server over SSH.</p>
55
2008-09-16T00:50:10Z
38,556,319
<p>Reached the same problem, but instead of "hacking" or emulating command line:</p> <p>Found this answer <a href="https://pypi.python.org/pypi/scp" rel="nofollow">here</a>.</p> <pre><code>from paramiko import SSHClient from scp import SCPClient ssh = SSHClient() ssh.load_system_host_keys() ssh.connect('example.com') with SCPClient(ssh.get_transport()) as scp: scp.put('test.txt', 'test2.txt') scp.get('test2.txt') </code></pre>
1
2016-07-24T20:12:13Z
[ "python", "ssh", "automation", "scp" ]
Send file using POST from a Python script
68,477
<p>Is there a way to send a file using POST from a Python script?</p>
70
2008-09-16T01:16:24Z
68,502
<p>Yes. You'd use the <code>urllib2</code> module, and encode using the <code>multipart/form-data</code> content type. Here is some sample code to get you started -- it's a bit more than just file uploading, but you should be able to read through it and see how it works:</p> <pre><code>user_agent = "image uploader" default_message = "Image $current of $total" import logging import os from os.path import abspath, isabs, isdir, isfile, join import random import string import sys import mimetypes import urllib2 import httplib import time import re def random_string (length): return ''.join (random.choice (string.letters) for ii in range (length + 1)) def encode_multipart_data (data, files): boundary = random_string (30) def get_content_type (filename): return mimetypes.guess_type (filename)[0] or 'application/octet-stream' def encode_field (field_name): return ('--' + boundary, 'Content-Disposition: form-data; name="%s"' % field_name, '', str (data [field_name])) def encode_file (field_name): filename = files [field_name] return ('--' + boundary, 'Content-Disposition: form-data; name="%s"; filename="%s"' % (field_name, filename), 'Content-Type: %s' % get_content_type(filename), '', open (filename, 'rb').read ()) lines = [] for name in data: lines.extend (encode_field (name)) for name in files: lines.extend (encode_file (name)) lines.extend (('--%s--' % boundary, '')) body = '\r\n'.join (lines) headers = {'content-type': 'multipart/form-data; boundary=' + boundary, 'content-length': str (len (body))} return body, headers def send_post (url, data, files): req = urllib2.Request (url) connection = httplib.HTTPConnection (req.get_host ()) connection.request ('POST', req.get_selector (), *encode_multipart_data (data, files)) response = connection.getresponse () logging.debug ('response = %s', response.read ()) logging.debug ('Code: %s %s', response.status, response.reason) def make_upload_file (server, thread, delay = 15, message = None, username = None, email = None, password = None): delay = max (int (delay or '0'), 15) def upload_file (path, current, total): assert isabs (path) assert isfile (path) logging.debug ('Uploading %r to %r', path, server) message_template = string.Template (message or default_message) data = {'MAX_FILE_SIZE': '3145728', 'sub': '', 'mode': 'regist', 'com': message_template.safe_substitute (current = current, total = total), 'resto': thread, 'name': username or '', 'email': email or '', 'pwd': password or random_string (20),} files = {'upfile': path} send_post (server, data, files) logging.info ('Uploaded %r', path) rand_delay = random.randint (delay, delay + 5) logging.debug ('Sleeping for %.2f seconds------------------------------\n\n', rand_delay) time.sleep (rand_delay) return upload_file def upload_directory (path, upload_file): assert isabs (path) assert isdir (path) matching_filenames = [] file_matcher = re.compile (r'\.(?:jpe?g|gif|png)$', re.IGNORECASE) for dirpath, dirnames, filenames in os.walk (path): for name in filenames: file_path = join (dirpath, name) logging.debug ('Testing file_path %r', file_path) if file_matcher.search (file_path): matching_filenames.append (file_path) else: logging.info ('Ignoring non-image file %r', path) total_count = len (matching_filenames) for index, file_path in enumerate (matching_filenames): upload_file (file_path, index + 1, total_count) def run_upload (options, paths): upload_file = make_upload_file (**options) for arg in paths: path = abspath (arg) if isdir (path): upload_directory (path, upload_file) elif isfile (path): upload_file (path) else: logging.error ('No such path: %r' % path) logging.info ('Done!') </code></pre>
18
2008-09-16T01:21:20Z
[ "python", "post", "file-upload", "http-post" ]
Send file using POST from a Python script
68,477
<p>Is there a way to send a file using POST from a Python script?</p>
70
2008-09-16T01:16:24Z
68,507
<p>This <a href="http://code.activestate.com/recipes/146306/" rel="nofollow">code</a> might be of use to you</p>
1
2008-09-16T01:22:03Z
[ "python", "post", "file-upload", "http-post" ]
Send file using POST from a Python script
68,477
<p>Is there a way to send a file using POST from a Python script?</p>
70
2008-09-16T01:16:24Z
75,158
<p>You may also want to have a look at <a href="http://code.google.com/p/httplib2/" rel="nofollow">httplib2</a>, with <a href="http://bitworking.org/projects/httplib2/doc/html/libhttplib2.html#examples" rel="nofollow">examples</a>. I find using httplib2 is more concise than using the built-in HTTP modules.</p>
0
2008-09-16T18:03:09Z
[ "python", "post", "file-upload", "http-post" ]
Send file using POST from a Python script
68,477
<p>Is there a way to send a file using POST from a Python script?</p>
70
2008-09-16T01:16:24Z
75,186
<p>Blatant self-promotion:</p> <p>check out my <a href="http://atlee.ca/software/poster/">poster</a> module for python. It handles the multipart/form-data encoding, as well as supporting streaming uploads (so you don't have to load the entire file into memory before submitting the HTTP POST request).</p>
59
2008-09-16T18:05:01Z
[ "python", "post", "file-upload", "http-post" ]
Send file using POST from a Python script
68,477
<p>Is there a way to send a file using POST from a Python script?</p>
70
2008-09-16T01:16:24Z
525,193
<p>Chris Atlee's <a href="http://atlee.ca/software/poster/" rel="nofollow">poster</a> library works really well for this (particularly the convenience function <code>poster.encode.multipart_encode()</code>). As a bonus, it supports streaming of large files without loading an entire file into memory. See also <a href="http://bugs.python.org/issue3244" rel="nofollow">Python issue 3244</a>.</p>
2
2009-02-08T05:20:36Z
[ "python", "post", "file-upload", "http-post" ]
Send file using POST from a Python script
68,477
<p>Is there a way to send a file using POST from a Python script?</p>
70
2008-09-16T01:16:24Z
7,969,778
<p>The only thing that stops you from using urlopen directly on a file object is the fact that the builtin file object lacks a <strong>len</strong> definition. A simple way is to create a subclass, which provides urlopen with the correct file. I have also modified the Content-Type header in the file below.</p> <pre><code>import os import urllib2 class EnhancedFile(file): def __init__(self, *args, **keyws): file.__init__(self, *args, **keyws) def __len__(self): return int(os.fstat(self.fileno())[6]) theFile = EnhancedFile('a.xml', 'r') theUrl = "http://example.com/abcde" theHeaders= {'Content-Type': 'text/xml'} theRequest = urllib2.Request(theUrl, theFile, theHeaders) response = urllib2.urlopen(theRequest) theFile.close() for line in response: print line </code></pre>
4
2011-11-01T16:43:03Z
[ "python", "post", "file-upload", "http-post" ]
Send file using POST from a Python script
68,477
<p>Is there a way to send a file using POST from a Python script?</p>
70
2008-09-16T01:16:24Z
10,234,640
<p>From <a href="http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file">http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file</a></p> <p>Requests makes it very simple to upload Multipart-encoded files:</p> <pre><code>&gt;&gt;&gt; r = requests.post('http://httpbin.org/post', files={'report.xls': open('report.xls', 'rb')}) </code></pre> <p>That's it. I'm not joking - this is one line of code. File was sent. Let's check:</p> <pre><code>&gt;&gt;&gt; r.text { "origin": "179.13.100.4", "files": { "report.xls": "&lt;censored...binary...data&gt;" }, "form": {}, "url": "http://httpbin.org/post", "args": {}, "headers": { "Content-Length": "3196", "Accept-Encoding": "identity, deflate, compress, gzip", "Accept": "*/*", "User-Agent": "python-requests/0.8.0", "Host": "httpbin.org:80", "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1" }, "data": "" } </code></pre>
101
2012-04-19T18:40:02Z
[ "python", "post", "file-upload", "http-post" ]
Send file using POST from a Python script
68,477
<p>Is there a way to send a file using POST from a Python script?</p>
70
2008-09-16T01:16:24Z
31,305,207
<p>Looks like python requests does not handle extremely large multi-part files.</p> <p>The documentation recommends you look into <code>requests-toolbelt</code>.</p> <p><a href="https://toolbelt.readthedocs.org/en/latest/uploading-data.html" rel="nofollow">Here's the pertinent page</a> from their documentation.</p>
3
2015-07-08T22:51:47Z
[ "python", "post", "file-upload", "http-post" ]
Send file using POST from a Python script
68,477
<p>Is there a way to send a file using POST from a Python script?</p>
70
2008-09-16T01:16:24Z
36,078,069
<pre><code>def visit_v2(device_code, camera_code): image1 = MultipartParam.from_file("files", "/home/yuzx/1.txt") image2 = MultipartParam.from_file("files", "/home/yuzx/2.txt") datagen, headers = multipart_encode([('device_code', device_code), ('position', 3), ('person_data', person_data), image1, image2]) print "".join(datagen) if server_port == 80: port_str = "" else: port_str = ":%s" % (server_port,) url_str = "http://" + server_ip + port_str + "/adopen/device/visit_v2" headers['nothing'] = 'nothing' request = urllib2.Request(url_str, datagen, headers) try: response = urllib2.urlopen(request) resp = response.read() print "http_status =", response.code result = json.loads(resp) print resp return result except urllib2.HTTPError, e: print "http_status =", e.code print e.read() </code></pre>
0
2016-03-18T06:59:16Z
[ "python", "post", "file-upload", "http-post" ]
Send file using POST from a Python script
68,477
<p>Is there a way to send a file using POST from a Python script?</p>
70
2008-09-16T01:16:24Z
37,142,773
<p>I am trying to test django rest api and its working for me:</p> <pre><code>def test_upload_file(self): filename = "/Users/Ranvijay/tests/test_price_matrix.csv" data = {'file': open(filename, 'rb')} client = APIClient() # client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) response = client.post(reverse('price-matrix-csv'), data, format='multipart') print response self.assertEqual(response.status_code, status.HTTP_200_OK) </code></pre>
1
2016-05-10T15:23:21Z
[ "python", "post", "file-upload", "http-post" ]
libxml2-p25 on OS X 10.5 needs sudo?
68,541
<p>When trying to use <code>libxml2</code> as myself I get an error saying the package cannot be found. If I run as as super user I am able to import fine.</p> <p>I have installed <code>python25</code> and all <code>libxml2</code> and <code>libxml2-py25</code> related libraries via fink and own the entire path including the library. Any ideas why I'd still need to sudo?</p>
0
2008-09-16T01:27:28Z
69,513
<p>Check your path (run 'echo $PATH')</p>
3
2008-09-16T05:01:08Z
[ "python", "osx", "libxml2" ]
libxml2-p25 on OS X 10.5 needs sudo?
68,541
<p>When trying to use <code>libxml2</code> as myself I get an error saying the package cannot be found. If I run as as super user I am able to import fine.</p> <p>I have installed <code>python25</code> and all <code>libxml2</code> and <code>libxml2-py25</code> related libraries via fink and own the entire path including the library. Any ideas why I'd still need to sudo?</p>
0
2008-09-16T01:27:28Z
70,895
<p>I would suspect the permissions on the library. Can you do a strace or similar to find out the filenames it's looking for, and then check the permissions on them?</p>
0
2008-09-16T10:04:43Z
[ "python", "osx", "libxml2" ]
libxml2-p25 on OS X 10.5 needs sudo?
68,541
<p>When trying to use <code>libxml2</code> as myself I get an error saying the package cannot be found. If I run as as super user I am able to import fine.</p> <p>I have installed <code>python25</code> and all <code>libxml2</code> and <code>libxml2-py25</code> related libraries via fink and own the entire path including the library. Any ideas why I'd still need to sudo?</p>
0
2008-09-16T01:27:28Z
77,114
<p>The path was the mistake. Thanks. I was looking at everything else to be wrong :-)</p>
0
2008-09-16T21:08:07Z
[ "python", "osx", "libxml2" ]
Are tuples more efficient than lists in Python?
68,630
<p>Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? </p>
101
2008-09-16T01:43:39Z
68,638
<p>Tuples should be slightly more efficient and because of that, faster, than lists because they are immutable.</p>
1
2008-09-16T01:45:39Z
[ "python", "performance", "python-internals" ]
Are tuples more efficient than lists in Python?
68,630
<p>Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? </p>
101
2008-09-16T01:43:39Z
68,712
<p>In general, you might expect tuples to be slightly faster. However you should definitely test your specific case (if the difference might impact the performance of your program -- remember "premature optimization is the root of all evil").</p> <p>Python makes this very easy: <a href="https://docs.python.org/2/library/timeit.html">timeit</a> is your friend.</p> <pre><code>$ python -m timeit "x=(1,2,3,4,5,6,7,8)" 10000000 loops, best of 3: 0.0388 usec per loop $ python -m timeit "x=[1,2,3,4,5,6,7,8]" 1000000 loops, best of 3: 0.363 usec per loop </code></pre> <p>and...</p> <pre><code>$ python -m timeit -s "x=(1,2,3,4,5,6,7,8)" "y=x[3]" 10000000 loops, best of 3: 0.0938 usec per loop $ python -m timeit -s "x=[1,2,3,4,5,6,7,8]" "y=x[3]" 10000000 loops, best of 3: 0.0649 usec per loop </code></pre> <p>So in this case, instantiation is almost an order of magnitude faster for the tuple, but item access is actually somewhat faster for the list! So if you're creating a few tuples and accessing them many many times, it may actually be faster to use lists instead.</p> <p>Of course if you want to <em>change</em> an item, the list will definitely be faster since you'd need to create an entire new tuple to change one item of it (since tuples are immutable).</p>
131
2008-09-16T01:57:10Z
[ "python", "performance", "python-internals" ]
Are tuples more efficient than lists in Python?
68,630
<p>Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? </p>
101
2008-09-16T01:43:39Z
68,817
<p>The <a href="https://docs.python.org/3/library/dis.html"><code>dis</code></a> module disassembles the byte code for a function and is useful to see the difference between tuples and lists.</p> <p>In this case, you can see that accessing an element generates identical code, but that assigning a tuple is much faster than assigning a list.</p> <pre><code>&gt;&gt;&gt; def a(): ... x=[1,2,3,4,5] ... y=x[2] ... &gt;&gt;&gt; def b(): ... x=(1,2,3,4,5) ... y=x[2] ... &gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(a) 2 0 LOAD_CONST 1 (1) 3 LOAD_CONST 2 (2) 6 LOAD_CONST 3 (3) 9 LOAD_CONST 4 (4) 12 LOAD_CONST 5 (5) 15 BUILD_LIST 5 18 STORE_FAST 0 (x) 3 21 LOAD_FAST 0 (x) 24 LOAD_CONST 2 (2) 27 BINARY_SUBSCR 28 STORE_FAST 1 (y) 31 LOAD_CONST 0 (None) 34 RETURN_VALUE &gt;&gt;&gt; dis.dis(b) 2 0 LOAD_CONST 6 ((1, 2, 3, 4, 5)) 3 STORE_FAST 0 (x) 3 6 LOAD_FAST 0 (x) 9 LOAD_CONST 2 (2) 12 BINARY_SUBSCR 13 STORE_FAST 1 (y) 16 LOAD_CONST 0 (None) 19 RETURN_VALUE </code></pre>
88
2008-09-16T02:13:29Z
[ "python", "performance", "python-internals" ]
Are tuples more efficient than lists in Python?
68,630
<p>Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? </p>
101
2008-09-16T01:43:39Z
70,968
<p>Tuples, being immutable, are more memory efficient; lists, for efficiency, overallocate memory in order to allow appends without constant <code>realloc</code>s. So, if you want to iterate through a constant sequence of values in your code (eg <code>for direction in 'up', 'right', 'down', 'left':</code>), tuples are preferred, since such tuples are pre-calculated in compile time.</p> <p>Access speeds should be the same (they are both stored as contiguous arrays in the memory).</p> <p>But, <code>alist.append(item)</code> is much preferred to <code>atuple+= (item,)</code> when you deal with mutable data. Remember, tuples are intended to be treated as records without field names.</p>
26
2008-09-16T10:16:52Z
[ "python", "performance", "python-internals" ]
Are tuples more efficient than lists in Python?
68,630
<p>Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? </p>
101
2008-09-16T01:43:39Z
71,295
<p>You should also consider the <code>array</code> module in the standard library if all the items in your list or tuple are of the same type. It can be faster and take less memory.</p>
6
2008-09-16T11:14:08Z
[ "python", "performance", "python-internals" ]
Are tuples more efficient than lists in Python?
68,630
<p>Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? </p>
101
2008-09-16T01:43:39Z
22,140,115
<p>There are several performance differences between tuples and lists when it comes to instantiation and retrieval of elements:</p> <ol> <li><p>Tuples containing immutable entries can be optimized into constants by Python's peephole optimizer. Lists, on the other hand, get build-up from scratch:</p> <pre><code>&gt;&gt;&gt; from dis import dis &gt;&gt;&gt; dis(compile("(10, 'abc')", '', 'eval')) 1 0 LOAD_CONST 2 ((10, 'abc')) 3 RETURN_VALUE &gt;&gt;&gt; dis(compile("[10, 'abc']", '', 'eval')) 1 0 LOAD_CONST 0 (10) 3 LOAD_CONST 1 ('abc') 6 BUILD_LIST 2 9 RETURN_VALUE </code></pre></li> <li><p>Internally, tuples are stored a little more efficiently than lists, and also tuples can be accessed slightly faster. </p> <p>Here is how the tuple <code>(10, 20)</code> is stored:</p> <pre><code>typedef struct { Py_ssize_t ob_refcnt; struct _typeobject *ob_type; Py_ssize_t ob_size; PyObject *ob_item[2]; /* store a pointer to 10 and a pointer to 20 */ } PyTupleObject; </code></pre> <p>Here is how the list <code>[10, 20]</code> is stored:</p> <pre><code>PyObject arr[2]; /* store a pointer to 10 and a pointer to 20 */ typedef struct { Py_ssize_t ob_refcnt; struct _typeobject *ob_type; Py_ssize_t ob_size; PyObject **ob_item = arr; /* store a pointer to the two-pointer array */ Py_ssize_t allocated; } PyListObject; </code></pre> <p>Note that the tuple object incorporates the two data pointers directly while the list object has an additional layer of indirection to an external array holding the two data pointers.</p></li> </ol>
26
2014-03-03T06:30:39Z
[ "python", "performance", "python-internals" ]
Static class variables in Python
68,645
<p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
1,015
2008-09-16T01:46:36Z
68,672
<p>Variables declared inside the class definition, but not inside a method are class or static variables:</p> <pre><code>&gt;&gt;&gt; class MyClass: ... i = 3 ... &gt;&gt;&gt; MyClass.i 3 </code></pre> <p>As @<a href="http://stackoverflow.com/questions/68645/static-class-variables-in-python#answer-69067">millerdev</a> points out, this creates a class-level "i" variable, but this is distinct from any instance-level "i" variable, so you could have</p> <pre><code>&gt;&gt;&gt; m = MyClass() &gt;&gt;&gt; m.i = 4 &gt;&gt;&gt; MyClass.i, m.i &gt;&gt;&gt; (3, 4) </code></pre> <p>This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.</p> <p>See <a href="https://docs.python.org/2/tutorial/classes.html#class-objects">what the Python tutorial has to say on the subject of classes and class objects</a>.</p> <p>@Steve Johnson has already answered regarding <a href="http://web.archive.org/web/20090214211613/http://pyref.infogami.com/staticmethod">static methods</a>, also documented under <a href="https://docs.python.org/2/library/functions.html#staticmethod">"Built-in Functions" in the Python Library Reference</a>.</p> <pre><code>class C: @staticmethod def f(arg1, arg2, ...): ... </code></pre> <p>@beidy recommends <a href="https://docs.python.org/2/library/functions.html#classmethod">classmethod</a>s over staticmethod, as the method then receives the class type as the first argument, but I'm still a little fuzzy on the advantages of this approach over staticmethod. If you are too, then it probably doesn't matter.</p>
1,030
2008-09-16T01:51:06Z
[ "python", "class", "methods", "static", "class-variables" ]
Static class variables in Python
68,645
<p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
1,015
2008-09-16T01:46:36Z
68,747
<p>Personally I would use a classmethod whenever I needed a static method. Mainly because I get the class as an argument.</p> <pre><code>class myObj(object): def myMethod(cls) ... myMethod = classmethod(myMethod) </code></pre> <p>or use a decorator</p> <pre><code>class myObj(object): @classmethod def myMethod(cls) </code></pre> <p>For static properties.. Its time you look up some python definition.. variable can always change. There are two types of them mutable and immutable.. Also, there are class attributes and instance attributes.. Nothing really like static attributes in the sense of java &amp; c++</p> <p>Why use static method in pythonic sense, if it has no relation whatever to the class! If I were you, I'd either use classmethod or define the method independent from the class.</p>
9
2008-09-16T02:02:45Z
[ "python", "class", "methods", "static", "class-variables" ]
Static class variables in Python
68,645
<p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
1,015
2008-09-16T01:46:36Z
68,770
<p>Static methods in python are called <a href="http://pyref.infogami.com/classmethod" rel="nofollow">classmethod</a>s. Take a look at the following code</p> <pre><code>class MyClass: def myInstanceMethod(self): print 'output from an instance method' @classmethod def myStaticMethod(cls): print 'output from a static method' MyClass.myInstanceMethod() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unbound method myInstanceMethod() must be called [...] MyClass.myStaticMethod() </code></pre> <p>output from a static method</p> <p>Notice that when we call the method <em>myInstanceMethod</em>, we get an error. This is because it requires that method be called on an instance of this class. The method <em>myStaticMethod</em> is set as a classmethod using the <a href="http://www.python.org/dev/peps/pep-0318/" rel="nofollow">decorator</a> <em>@classmethod</em>.</p> <p>Just for kicks and giggles, we could call <em>myInstanceMethod</em> on the class by passing in an instance of the class, like so:</p> <pre><code>&gt;&gt;&gt; MyClass.myInstanceMethod(MyClass()) output from an instance method </code></pre>
5
2008-09-16T02:05:49Z
[ "python", "class", "methods", "static", "class-variables" ]
Static class variables in Python
68,645
<p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
1,015
2008-09-16T01:46:36Z
69,067
<p>@Blair Conrad said static variables declared inside the class definition, but not inside a method are class or "static" variables:</p> <pre><code>&gt;&gt;&gt; class Test(object): ... i = 3 ... &gt;&gt;&gt; Test.i 3 </code></pre> <p>There are a few gotcha's here. Carrying on from the example above:</p> <pre><code>&gt;&gt;&gt; t = Test() &gt;&gt;&gt; t.i # static variable accessed via instance 3 &gt;&gt;&gt; t.i = 5 # but if we assign to the instance ... &gt;&gt;&gt; Test.i # we have not changed the static variable 3 &gt;&gt;&gt; t.i # we have overwritten Test.i on t by creating a new attribute t.i 5 &gt;&gt;&gt; Test.i = 6 # to change the static variable we do it by assigning to the class &gt;&gt;&gt; t.i 5 &gt;&gt;&gt; Test.i 6 &gt;&gt;&gt; u = Test() &gt;&gt;&gt; u.i 6 # changes to t do not affect new instances of Test # Namespaces are one honking great idea -- let's do more of those! &gt;&gt;&gt; Test.__dict__ {'i': 6, ...} &gt;&gt;&gt; t.__dict__ {'i': 5} &gt;&gt;&gt; u.__dict__ {} </code></pre> <p>Notice how the instance variable <code>t.i</code> got out of sync with the "static" class variable when the attribute <code>i</code> was set directly on <code>t</code>. This is because <code>i</code> was re-bound within the <code>t</code> namespace, which is distinct from the <code>Test</code> namespace. If you want to change the value of a "static" variable, you must change it within the scope (or object) where it was originally defined. I put "static" in quotes because Python does not really have static variables in the sense that C++ and Java do.</p> <p>Although it doesn't say anything specific about static variables or methods, the <a href="http://docs.python.org/tut/">Python tutorial</a> has some relevant information on <a href="https://docs.python.org/2/tutorial/classes.html">classes and class objects</a>. </p> <p>@Steve Johnson also answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.</p> <pre><code>class Test(object): @staticmethod def f(arg1, arg2, ...): ... </code></pre> <p>@beid also mentioned classmethod, which is similar to staticmethod. A classmethod's first argument is the class object. Example:</p> <pre><code>class Test(object): i = 3 # class (or static) variable @classmethod def g(cls, arg): # here we can use 'cls' instead of the class name (Test) if arg &gt; cls.i: cls.i = arg # would the the same as Test.i = arg1 </code></pre>
400
2008-09-16T03:04:08Z
[ "python", "class", "methods", "static", "class-variables" ]
Static class variables in Python
68,645
<p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
1,015
2008-09-16T01:46:36Z
79,840
<p>To avoid any potential confusion, I would like to contrast static variables and immutable objects.</p> <p>Some primitive object types like integers, floats, strings, and touples are immutable in Python. This means that the object that is referred to by a given name cannot change if it is of one of the aforementioned object types. The name can be reassigned to a different object, but the object itself may not be changed.</p> <p>Making a variable static takes this a step further by disallowing the variable name to point to any object but that to which it currently points. (Note: this is a general software concept and not specific to Python; please see others' posts for information about implementing statics in Python).</p>
2
2008-09-17T04:01:08Z
[ "python", "class", "methods", "static", "class-variables" ]
Static class variables in Python
68,645
<p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
1,015
2008-09-16T01:46:36Z
81,002
<p>You can also add class variables to classes on the fly</p> <pre><code>&gt;&gt;&gt; class X: ... pass ... &gt;&gt;&gt; X.bar = 0 &gt;&gt;&gt; x = X() &gt;&gt;&gt; x.bar 0 &gt;&gt;&gt; x.foo Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; AttributeError: X instance has no attribute 'foo' &gt;&gt;&gt; X.foo = 1 &gt;&gt;&gt; x.foo 1 </code></pre> <p>And class instances can change class variables</p> <pre><code>class X: l = [] def __init__(self): self.l.append(1) print X().l print X().l &gt;python test.py [1] [1, 1] </code></pre>
19
2008-09-17T08:06:22Z
[ "python", "class", "methods", "static", "class-variables" ]