Re: Conditional decoration
On 18/06/2012 23:16, Roy Smith wrote: Is there any way to conditionally apply a decorator to a function? For example, in django, I want to be able to control, via a run-time config flag, if a view gets decorated with @login_required(). @login_required() def my_view(request): pass A decorator is just syntactic sugar for function application after the definition. This: @deco def func(): pass is just another way of writing: def func(): pass func = deco(func) Not as neat, but you can make it conditional. -- http://mail.python.org/mailman/listinfo/python-list
Re: Conditional decoration
On 6/18/2012 3:16 PM Roy Smith said... Is there any way to conditionally apply a decorator to a function? For example, in django, I want to be able to control, via a run-time config flag, if a view gets decorated with @login_required(). @login_required() def my_view(request): pass class myDecorator(object): def __init__(self, f): self.f = f def __call__(self): print "Entering", self.f.__name__ self.f() print "Exited", self.f.__name__ def null(a): return a #if condition: myDecorator = null @myDecorator def aFunction(): print "aFunction running" aFunction() Cobbled together from http://www.chrisevans3d.com/pub_blog/?p=530 and http://stackoverflow.com/questions/3687046/python-sphinx-autodoc-and-decorated-members HTH Emile -- http://mail.python.org/mailman/listinfo/python-list
Read STDIN as bytes rather than a string
I tried this: Python 3.2.2 (default, Feb 24 2012, 20:07:04) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> import io >>> fh = io.open(sys.stdin) Traceback (most recent call last): File "", line 1, in TypeError: invalid file: <_io.TextIOWrapper name='' mode='r' encoding='UTF-8'> >>> fh = io.open(sys.stdin, "rb") Traceback (most recent call last): File "", line 1, in TypeError: invalid file: <_io.TextIOWrapper name='' mode='r' encoding='UTF-8'> -- http://mail.python.org/mailman/listinfo/python-list
Re: lazy evaluation of a variable
On 06/17/2012 11:35 PM, Gelonida N wrote: Hi, I'm not sure whether what I ask for is impossible, but would know how others handle such situations. I'm having a module, which should lazily evaluate one of it's variables. Meaning that it is evaluated only if anybody tries to use this variable. At the moment I don't know how to do this and do therefore following: ### mymodule.py ### var = None def get_var(): global var if var is not None: return var var = something_time_consuming() Now the importing code would look like import mymodule def f(): var = mymodule.get_var() The disadvantage is, that I had to change existing code directly accessing the variable. I wondered if there were any way to change mymodule.py such, that the importing code could just access a variable and the lazy evaluation would happen transparently. import mymodule def f(): var = mymodule.var Thanks everybody for your responses. This gave me quite some ideas. It seems, that none of the solutions would allow to have the changes only in the module. More out of curiosity than out of real necessity I wanted to know, whether it would be possible to hide the lazy evaluation from already existing code, that has already the import statement written. So the question basically boiled down to "can one make 'properties' for modules?" It seems no. Probably there aren't many real use cases except for monkey patching libraries or for logging accesses to a module's variable -- http://mail.python.org/mailman/listinfo/python-list
Re: Read STDIN as bytes rather than a string
On Mon, Jun 18, 2012 at 4:13 PM, Jason Friedman wrote: > I tried this: > > Python 3.2.2 (default, Feb 24 2012, 20:07:04) > [GCC 4.6.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. import sys import io fh = io.open(sys.stdin) > Traceback (most recent call last): > File "", line 1, in > TypeError: invalid file: <_io.TextIOWrapper name='' mode='r' > encoding='UTF-8'> fh = io.open(sys.stdin, "rb") > Traceback (most recent call last): > File "", line 1, in > TypeError: invalid file: <_io.TextIOWrapper name='' mode='r' > encoding='UTF-8'> > -- You want to read from sys.stdin.buffer -- http://mail.python.org/mailman/listinfo/python-list
Re: Read STDIN as bytes rather than a string
Am 19.06.2012 01:13, schrieb Jason Friedman: > I tried this: sys.stdin wraps a buffered reader which itself wraps a raw file reader. >>> sys.stdin <_io.TextIOWrapper name='' mode='r' encoding='UTF-8'> >>> sys.stdin.buffer <_io.BufferedReader name=''> >>> sys.stdin.buffer.raw <_io.FileIO name='' mode='rb'> You should read from sys.stdin.buffer unless you really need the bare metal. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Read STDIN as bytes rather than a string
> sys.stdin wraps a buffered reader which itself wraps a raw file reader. > sys.stdin > <_io.TextIOWrapper name='' mode='r' encoding='UTF-8'> sys.stdin.buffer > <_io.BufferedReader name=''> sys.stdin.buffer.raw > <_io.FileIO name='' mode='rb'> > > You should read from sys.stdin.buffer unless you really need the bare > metal. > Thank you, and just to close the loop: $ cat ~/my-input.py #!/opt/python/bin/python3 import sys print(sys.stdin.buffer.read()) $ echo hello | ~/my-input.py b'hello\n' -- http://mail.python.org/mailman/listinfo/python-list
Re: Read STDIN as bytes rather than a string
Which leads me to another question ... how can I debug these things? $ echo 'hello' | python3 -m pdb ~/my-input.py > /home/jason/my-input.py(2)() -> import sys (Pdb) *** NameError: name 'hello' is not defined -- http://mail.python.org/mailman/listinfo/python-list
Re: Conditional decoration
On Mon, Jun 18, 2012 at 6:49 PM, Emile van Sebille wrote: > On 6/18/2012 3:16 PM Roy Smith said... > class myDecorator(object): > def __init__(self, f): > self.f = f > def __call__(self): > print "Entering", self.f.__name__ > self.f() > print "Exited", self.f.__name__ I dunno about other people, but I generally avoid class decorators because they do not behave the way functions do when applied as a decorator for a method. This is a decorator taken out of some of my own source code. I was mostly dicking around with things, as opposed to actually coding. The docstring was even more ridiculous. from functools import reduce def rapply(*args): """apply(f, ...) <-> rapply(..., f)""" return args[-1](*args[:-1]) def condecorator(condition, *decorators): if condition: return lambda f: reduce(rapply, reversed(decorators), f) else: return lambda f: f Example usage: @condecorator(condition, decorator1, decorator2) def decorated(...): ... equivalent to: def decorated(...): ... if condition: decorated = decorator1(decorator2(decorated)) -- Devin -- http://mail.python.org/mailman/listinfo/python-list
Re: Conditional decoration
Roy Smith wrote in news:[email protected] in gmane.comp.python.general: > Is there any way to conditionally apply a decorator to a function? > For example, in django, I want to be able to control, via a run-time > config flag, if a view gets decorated with @login_required(). > > @login_required() > def my_view(request): > pass You need to create a decorator that calls either the original function or the decorated funtion, depending on your condition, Something like (untested): def conditional_login_required( f ): _login_required = login_required()(f) def decorated( request ): if condition == "use-login": return _login_required( request ) else: return f( request ) return decorated @conditional_login_required def my_view(request): pass Replace (condition == "use-login") with whatever your "run-time control flag" is. -- Rob. -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking compatibility of a script across Python versions automatically
On 6/18/2012 3:24 PM, Andrew Berg wrote: Are there any tools out there that will parse a script and tell me if it is compatible with an arbitrary version of Python and highlight any Not that I know of. incompatibilities? I need to check a few of my scripts that target 3.2 to see if I can make them compatible with 3.0 and 3.1 if they aren't already. Forget about 3.0. Really. As for 3.1 versus 3.2, there were no core syntax changes in 3.2. There were a few, but only a few, enhancements in builtin classes. If you have a decent test suite, just run it under 3.1. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
"constant sharing" works differently in REPL than in script ?
Listening to 'Radio Free Python' episode 8 (http://radiofreepython.com/episodes/8/ - around about the 30 minute mark) I heard that Python pre creates some integer constants to avoid a proliferation of objects with the same value. I was interested in this and so I decided to try it out. First I did this at the prompt : >>> c = 1 >>> print id(1) 26906152 >>> print id(c) 26906152 >>> c is 1 True So that matched what I'd heard and then I did this to test the limits of it : >>> c = 259 >>> print id(259) 26167488 >>> print id(c) 26167512 >>> c is 259 False And that was reasonable too as the podcast mentioned it was only done for a small set of integers around zero. However when I wrote this script : c = 259 print id(259) print id(c) if c is 259: print "%s - yes" % (c) else: print "%s - no " % (c) I got this output : C:\data\src\Python\foo>python untitled-2.py 26760884 26760884 259 - yes So what's going on here. The script seems to be sharing objects in a way the REPL isn't ? Can anyone explain please ? BTW this is all on : Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 . -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter binding question
On Monday, June 18, 2012 1:21:02 PM UTC-5, Frederic Rentsch wrote:
> Hi All,
>
> For most of an afternoon I've had that stuck-in-a-dead-end feeling
> probing to no avail all permutations formulating bindings, trying to
> make sense of manuals and tutorials. Here are my bindings:
>
>label_frame.bind ('', self.color_selected)
>label_frame.bind ('', self.color_selectable)
>label_frame.bind ('', self.pick_record)
>label_frame.bind ('', self.info_profile)
This example is useless to me. As a matter of fact, your whole explanation of
the problem is ambitious at best. But you do realize that by binding both the
click and release of a mouse button to the same callback you will call the
callback twice?
Try to create a simplistic and generic example of the problem. Most times
you'll find the flaw. Most code should start as template that prints messages
to stdout. Large applications are built by taking babysteps. Not by jumping out
the fire and into the frying pan!
WARNING: Debugging large chucks of spaghetti code is bad for your brain! Tip of
the day: DIVIDE AND CONQUER!
## START CODE ##
from __future__ import print_function
import Tkinter as tk
root = tk.Tk()
root.geometry('200x200+20+20')
root.bind("", lambda e:print("Enter"))
root.bind("", lambda e:print("Leave"))
root.bind("",
lambda e:print("ButtonOneRelease"))
root.bind("",
lambda e:print("ButtonThreeRelease"))
root.mainloop()
## END CODE ##
Q1: Now, what exactly is the problem? Hmm???
Q2: Can you modify this code to correct the problem? Hmm???
Q3: Why are there so many inconsistencies in the Tkinter API? Hmm???
Tip: NEVER bind "ButtonClick" to trigger a callback (ESPECIALLY FOR A BUTTON
CALLBACK!!!). ONLY bind "ButtonRelease". Why? Well because if the user
accidentally clicks the button, he can move his pointer beyond the boundaries
of the button and then release the mouse "button" WITHOUT triggering the
callback. All good GUI coders follow this design pattern. (Except in certain
cases where you want a mouse click to trigger an action quickly; like a Listbox
item or menu, or whatever.)
if GUI.ergonomics < optimal:
raise NeophyteError("Do not pass GUI. Do not collect 100 dollars!")
> and work fine. But when I try to select an entered item,
> the moment I push the left or the right button, color_selectable ()
> and color_selected () are called again in rapid succession.
That does not make sense. Are you calling the method "w.update()" anywhere in
the callback; or as a consequence of the callback?
> The same
> effect happens even when I push the middle mouse button which is
> rather weird, because it has no binding.
Not necessarily. Many of the Tk widgets come prepackaged with annoying little
default bindings that would the test the patience of a saint. Like, for
example, the Tkinter.Text widget. It has a nasty little default binding to
paste the cut buffer contents when you press MouseButtonTwo. And since it also
has a default binding of using MouseButtonTwo+MouseMotion to scroll vertically,
you find yourself inserting cut buffers everywhere!
> The behavior suggests that
> no event can occur on an entered widget before it is left again and
> if an event other that comes in, the callback gets
> called automatically. That can't be right, though. It isn't possible
> to click an item without entering it.
Interesting observation. I would say your code is too complicated to properly
debug. You need to divide and conquer this spaghetti mess.
--
http://mail.python.org/mailman/listinfo/python-list
Re: lazy evaluation of a variable
On Sunday, June 17, 2012 6:01:03 PM UTC-5, Steven D'Aprano wrote: > One day, in my Copious Spare Time, I intend to write a proper feature > request and/or PEP for such a feature. Obviously the absolute earliest > such a feature could be introduced is Python 3.4, about 18 months from > now. (Although frankly, I would imagine significant opposition from the > more conservative Python developers.) Well these conservatives must have been suffering from chronic mononucleosis because i have never heard a peep from them! I wish they would "grow a pair" and speak up a bit more often because the language would benefit greatly from some austerity measures, strong leadership, and most of all; some Gawd damned consistency! -- http://mail.python.org/mailman/listinfo/python-list
Re: "constant sharing" works differently in REPL than in script ?
On Mon, Jun 18, 2012 at 7:52 PM, wrote: > Listening to 'Radio Free Python' episode 8 > (http://radiofreepython.com/episodes/8/ - around about the 30 minute mark) I > heard that Python pre creates some integer constants to avoid a proliferation > of objects with the same value. > > I was interested in this and so I decided to try it out. > > First I did this at the prompt : > c = 1 print id(1) > 26906152 print id(c) > 26906152 c is 1 > True > > So that matched what I'd heard and then I did this to test the limits of it : > c = 259 print id(259) > 26167488 print id(c) > 26167512 c is 259 > False > > And that was reasonable too as the podcast mentioned it was only done for a > small set of integers around zero. > > However when I wrote this script : > > c = 259 > print id(259) > print id(c) > if c is 259: > print "%s - yes" % (c) > else: > print "%s - no " % (c) > > I got this output : > > C:\data\src\Python\foo>python untitled-2.py > 26760884 > 26760884 > 259 - yes > > So what's going on here. The script seems to be sharing objects in a way the > REPL isn't ? > > Can anyone explain please ? > > BTW this is all on : Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC > v.1500 32 bit (Intel)] on win32 . > Python the language doesn't specify anything about this sort of behavior. CPython the implementation does all sorts of optimizations to make code run more efficiently. Caching integers is one of those optimizations. In the case where the code is compiled all at once (as in the script) instead of one line at a time (the REPL), it can do more optimizations. But as I said, none of this is in the specification so you shouldn't rely on it. The general rule for the "is" operator is that unless you specifically know that you need it, don't use it. -- http://mail.python.org/mailman/listinfo/python-list
Pymongo Error
Hi all,
I tried Django with Mongodb while running manage.py syncdb I endup with
this error
note : it works fine with sqlite and mysql db
(django-1.3)ranjith@ranjith:~/
sandbox/python-box/hukkster-core-site/hukk$ ./manage.py syncdb
/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/pymongo/connection.py:385:
UserWarning: must provide a username and password to authenticate to
hukkster_testing
"to authenticate to %s" % (db,))
Creating tables ...
Traceback (most recent call last):
File "./manage.py", line 14, in
execute_manager(settings)
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/__init__.py",
line 438, in execute_manager
utility.execute()
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/__init__.py",
line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/base.py",
line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/base.py",
line 220, in execute
output = self.handle(*args, **options)
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/base.py",
line 351, in handle
return self.handle_noargs(**options)
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.py",
line 109, in handle_noargs
emit_post_sync_signal(created_models, verbosity, interactive, db)
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/sql.py",
line 190, in emit_post_sync_signal
interactive=interactive, db=db)
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/dispatch/dispatcher.py",
line 172, in send
response = receiver(signal=self, sender=sender, **named)
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/contrib/auth/management/__init__.py",
line 41, in create_permissions
"content_type", "codename"
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/db/models/query.py",
line 107, in _result_iter
self._fill_cache()
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/db/models/query.py",
line 772, in _fill_cache
self._result_cache.append(self._iter.next())
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/db/models/query.py",
line 959, in iterator
for row in self.query.get_compiler(self.db).results_iter():
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py",
line 229, in results_iter
for entity in self.build_query(fields).fetch(low_mark, high_mark):
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py",
line 290, in build_query
query.order_by(self._get_ordering())
File
"/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py",
line 339, in _get_ordering
raise DatabaseError("Ordering can't span tables on non-relational
backends (%s)" % order)
django.db.utils.DatabaseError: Ordering can't span tables on non-relational
backends (content_type__app_label)
DB settings in settings.py
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': 'helloworld',
'USER': '',
'PASSWORD': '12424214',
'HOST': 'mongodb://staff.mongohq.com/',
'PORT': 'X',
},
}
my requirement packages,
Django==1.3
dictshield==0.4.4
django-mongodb-engine==0.4.0
django-social-auth==0.6.9
djangotoolbox==0.0.1
httplib2==0.7.4
mongoengine==0.6.10
mongokit==0.8
oauth2==1.5.211
pymongo==2.2
python-openid==2.2.5
simplejson==2.5.2
wsgiref==0.1.2
Please point me what i missed here...
--
Cheers,
Ranjith Kumar K,
Chennai.
http://ranjithtenz.wordpress.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: [chennaipy 1376] Pymongo Error
Are you using django-nonrel or basic django version?
Check out http://www.allbuttonspressed.com/projects/django-nonrel
cheers
Ramesh
On Tue, Jun 19, 2012 at 10:52 AM, Ranjith Kumar wrote:
> Hi all,
> I tried Django with Mongodb while running manage.py syncdb I endup with
> this error
>
> note : it works fine with sqlite and mysql db
>
> (django-1.3)ranjith@ranjith:~/
> sandbox/python-box/hukkster-core-site/hukk$ ./manage.py syncdb
> /home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/pymongo/connection.py:385:
> UserWarning: must provide a username and password to authenticate to
> hukkster_testing
> "to authenticate to %s" % (db,))
> Creating tables ...
> Traceback (most recent call last):
> File "./manage.py", line 14, in
> execute_manager(settings)
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/__init__.py",
> line 438, in execute_manager
> utility.execute()
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/__init__.py",
> line 379, in execute
> self.fetch_command(subcommand).run_from_argv(self.argv)
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/base.py",
> line 191, in run_from_argv
> self.execute(*args, **options.__dict__)
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/base.py",
> line 220, in execute
> output = self.handle(*args, **options)
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/base.py",
> line 351, in handle
> return self.handle_noargs(**options)
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.py",
> line 109, in handle_noargs
> emit_post_sync_signal(created_models, verbosity, interactive, db)
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/sql.py",
> line 190, in emit_post_sync_signal
> interactive=interactive, db=db)
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/dispatch/dispatcher.py",
> line 172, in send
> response = receiver(signal=self, sender=sender, **named)
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/contrib/auth/management/__init__.py",
> line 41, in create_permissions
> "content_type", "codename"
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/db/models/query.py",
> line 107, in _result_iter
> self._fill_cache()
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/db/models/query.py",
> line 772, in _fill_cache
> self._result_cache.append(self._iter.next())
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/db/models/query.py",
> line 959, in iterator
> for row in self.query.get_compiler(self.db).results_iter():
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py",
> line 229, in results_iter
> for entity in self.build_query(fields).fetch(low_mark, high_mark):
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py",
> line 290, in build_query
> query.order_by(self._get_ordering())
> File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py",
> line 339, in _get_ordering
> raise DatabaseError("Ordering can't span tables on non-relational
> backends (%s)" % order)
> django.db.utils.DatabaseError: Ordering can't span tables on
> non-relational backends (content_type__app_label)
>
>
> DB settings in settings.py
>
> DATABASES = {
> 'default': {
> 'ENGINE': 'django_mongodb_engine',
> 'NAME': 'helloworld',
> 'USER': '',
> 'PASSWORD': '12424214',
> 'HOST': 'mongodb://staff.mongohq.com/',
> 'PORT': 'X',
> },
> }
>
> my requirement packages,
> Django==1.3
> dictshield==0.4.4
> django-mongodb-engine==0.4.0
> django-social-auth==0.6.9
> djangotoolbox==0.0.1
> httplib2==0.7.4
> mongoengine==0.6.10
> mongokit==0.8
> oauth2==1.5.211
> pymongo==2.2
> python-openid==2.2.5
> simplejson==2.5.2
> wsgiref==0.1.2
>
> Please point me what i missed here...
>
> --
> Cheers,
> Ranjith Kumar K,
> Chennai.
>
> http://ranjithtenz.wordpress.com
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Chennaipy" group.
> Wiki at http://nrcfosshelpline.in/chennaipy/
> To post to this group, send email to [email protected]
> To unsubscribe from this group, send email to
> [email protected]
> For more options, visit this group at
> http://groups.google.com/group/chennaipy?hl=en
--
http://mail.python.org/mailman/listinfo/pyth
Re: Checking compatibility of a script across Python versions automatically
Andrew Berg, 18.06.2012 21:24: > Are there any tools out there that will parse a script and tell me if it > is compatible with an arbitrary version of Python and highlight any > incompatibilities? I need to check a few of my scripts that target 3.2 > to see if I can make them compatible with 3.0 and 3.1 if they aren't > already. I found pyqver, but it isn't accurate (at least for 3.2/3.3 > scripts) and hasn't been updated in 2 years. I could look over the docs > and do it manually, but one of the scripts isn't small, so I'd prefer > not to. My advice: write a good test suite for your code and use something like tox to run it under the various Python versions that you want to support. No static analysis tool will ever be able to find all portability problems. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: "constant sharing" works differently in REPL than in script ?
[email protected] wrote: > Listening to 'Radio Free Python' episode 8 > (http://radiofreepython.com/episodes/8/ - around about the 30 minute mark) > I heard that Python pre creates some integer constants to avoid a > proliferation of objects with the same value. > > I was interested in this and so I decided to try it out. > > First I did this at the prompt : > c = 1 print id(1) > 26906152 print id(c) > 26906152 c is 1 > True > > So that matched what I'd heard and then I did this to test the limits of > it : > c = 259 print id(259) > 26167488 print id(c) > 26167512 c is 259 > False > > And that was reasonable too as the podcast mentioned it was only done for > a small set of integers around zero. > > However when I wrote this script : > > c = 259 > print id(259) > print id(c) > if c is 259: > print "%s - yes" % (c) > else: > print "%s - no " % (c) > > I got this output : > > C:\data\src\Python\foo>python untitled-2.py > 26760884 > 26760884 > 259 - yes > > So what's going on here. The script seems to be sharing objects in a way > the REPL isn't ? > > Can anyone explain please ? As Benjamin wrote, this is a compile-time optimization (and you shouldn't rely on it). You can replicate it on the commandline: >>> a = 300 >>> b = 300 >>> a is b False >>> c = 300; d = 300 >>> c is d True Looking under the hood there's only one value for both constants: >>> import dis >>> code = compile("x = 300; y = 300", "", "exec") >>> code.co_consts (300, None) The generated bytecode is: >>> dis.dis(code) 1 0 LOAD_CONST 0 (300) 3 STORE_NAME 0 (x) 6 LOAD_CONST 0 (300) 9 STORE_NAME 1 (y) 12 LOAD_CONST 1 (None) 15 RETURN_VALUE -- http://mail.python.org/mailman/listinfo/python-list
Help On Paramiko
Howdy All,
I am trying to use paramiko to automate logging in to remote unix machines and
executing some commands there.
When I normally do ssh from my linux machine (with Python 2.6) to this machine
a different '>' prompt comes. It's a device specific custom prompt.
After I run 'enable' command here, a new prompt opens up. '#' which is also
custom prompt.
Then I need to run 'configure terminal' there. And then some more device
specific commands.
i.e.
{{{
Linux # Ssh [email protected]
Ø Enable
# configure terminal
#
}}}
Can this be done using paramiko?
I tried with:
{{{
import paramiko
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('xx.xx.xx.xx', username='admin', password='')
stdin, stdout, stderr = client.exec_command('enable')
#stdin.write('configure t')
print(stdout.readlines())
}}}
(There is no passwd for username admin.)
o/p
['UNIX shell commands cannot be executed using this account.\n']
Any suggestions?
Thanks
Nikunj
--
http://mail.python.org/mailman/listinfo/python-list
Re: [BangPypers] Help On Paramiko
Fabric is a library built on paramiko that gives you abstractions so
that you don't have to worry about things at such a fine grained
level. Perhaps you should try using that.
writes:
> Howdy All,
>
> I am trying to use paramiko to automate logging in to remote unix machines
> and executing some commands there.
> When I normally do ssh from my linux machine (with Python 2.6) to this
> machine a different '>' prompt comes. It's a device specific custom prompt.
> After I run 'enable' command here, a new prompt opens up. '#' which is also
> custom prompt.
> Then I need to run 'configure terminal' there. And then some more device
> specific commands.
>
> i.e.
> {{{
> Linux # Ssh [email protected]
>
> Ø Enable
> # configure terminal
> #
> }}}
>
> Can this be done using paramiko?
> I tried with:
>
> {{{
> import paramiko
>
> client = paramiko.SSHClient()
> client.load_system_host_keys()
> client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
> client.connect('xx.xx.xx.xx', username='admin', password='')
> stdin, stdout, stderr = client.exec_command('enable')
> #stdin.write('configure t')
> print(stdout.readlines())
>
> }}}
> (There is no passwd for username admin.)
>
>
> o/p
> ['UNIX shell commands cannot be executed using this account.\n']
>
> Any suggestions?
>
> Thanks
> Nikunj
> ___
> BangPypers mailing list
> [email protected]
> http://mail.python.org/mailman/listinfo/bangpypers
>
--
Cordially,
Noufal
http://nibrahim.net.in
--
http://mail.python.org/mailman/listinfo/python-list
post init call
class Shape(object): def __init__(self, shapename): self.shapename = shapename def update(self): print "update" class ColoredShape(Shape): def __init__(self, color): Shape.__init__(self, color) self.color = color print 1 print 2 print 3 self.update() User can sub-class 'Shape' and create custom shapes. How ever user must call 'self.update()' as the last argument when ever he is sub-classing 'Shape'. I would like to know if it's possible to call 'self.update()' automatically after the __init__ of sub-class is done? Cheers -- http://mail.python.org/mailman/listinfo/python-list
Py3.3 unicode literal and input()
What is input() supposed to return?
>>> u'a' == 'a'
True
>>>
>>> r1 = input(':')
:a
>>> r2 = input(':')
:u'a'
>>> r1 == r2
False
>>> type(r1), len(r1)
(, 1)
>>> type(r2), len(r2)
(, 4)
>>>
---
sys.argv?
jmf
--
http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On Mon, Jun 18, 2012 at 1:19 AM, jmfauth wrote:
> What is input() supposed to return?
>
u'a' == 'a'
> True
r1 = input(':')
> :a
r2 = input(':')
> :u'a'
r1 == r2
> False
type(r1), len(r1)
> (, 1)
type(r2), len(r2)
> (, 4)
>
> ---
>
> sys.argv?
>
> jmf
Python 3 made several backwards-incompatible changes over Python 2.
First of all, input() in Python 3 is equivalent to raw_input() in
Python 2. It always returns a string. If you want the equivalent of
Python 2's input(), eval the result. Second, Python 3 is now unicode
by default. The "str" class is a unicode string. There is a separate
bytes class, denoted by b"", for byte strings. The u prefix is only
there to make it easier to port a codebase from Python 2 to Python 3.
It doesn't actually do anything.
--
http://mail.python.org/mailman/listinfo/python-list
Re: post init call
Am 18.06.2012 09:10, schrieb Prashant: > class Shape(object): > def __init__(self, shapename): > self.shapename = shapename > > > def update(self): > print "update" > > class ColoredShape(Shape): > def __init__(self, color): > Shape.__init__(self, color) Two things here: 1. You pass "color" as "shapename" to the baseclass' initialisation function, which is a bit surprising. 2. You can use super(ColoredShape, self).__init__(color) or even super(self).__init__(color). > User can sub-class 'Shape' and create custom shapes. How ever user > must call 'self.update()' as the last argument when ever he is > sub-classing 'Shape'. > I would like to know if it's possible to call 'self.update()' > automatically after the __init__ of sub-class is done? You might be able to, by hacking on the (meta?) class and how/when things are constructed. I'm not sure how to approach that though. What I would do is to use lazy initialisation, i.e. call update() when it is actually needed. For that, you could create a decorator and put it on all methods that require this initialisation. Good luck! Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On 18 juin, 10:28, Benjamin Kaplan wrote:
> On Mon, Jun 18, 2012 at 1:19 AM, jmfauth wrote:
> > What is input() supposed to return?
>
> u'a' == 'a'
> > True
>
> r1 = input(':')
> > :a
> r2 = input(':')
> > :u'a'
> r1 == r2
> > False
> type(r1), len(r1)
> > (, 1)
> type(r2), len(r2)
> > (, 4)
>
> > ---
>
> > sys.argv?
>
> > jmf
>
> Python 3 made several backwards-incompatible changes over Python 2.
> First of all, input() in Python 3 is equivalent to raw_input() in
> Python 2. It always returns a string. If you want the equivalent of
> Python 2's input(), eval the result. Second, Python 3 is now unicode
> by default. The "str" class is a unicode string. There is a separate
> bytes class, denoted by b"", for byte strings. The u prefix is only
> there to make it easier to port a codebase from Python 2 to Python 3.
> It doesn't actually do anything.
It does. I shew it!
Related:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/3aefd602507d2fbe#
http://mail.python.org/pipermail/python-dev/2012-June/120341.html
jmf
--
http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On Mon, 18 Jun 2012 01:19:32 -0700, jmfauth wrote:
> What is input() supposed to return?
Whatever you type.
u'a' == 'a'
> True
This demonstrates that in Python 3.3, u'a' gives a string equal to 'a'.
r1 = input(':')
> :a
Since you typed the letter a, r1 is the string "a" (a single character).
r2 = input(':')
> :u'a'
Since you typed four characters, namely lowercase u, single quote,
lowercase a, single quote, r2 is the string "u'a'" (four characters).
r1 == r2
> False
type(r1), len(r1)
> (, 1)
type(r2), len(r2)
> (, 4)
If you call print(r1) and print(r2), that will show you what they hold.
If in doubt, calling print(repr(r1)) will show extra information about
the object.
> sys.argv?
What about it?
>
> jmf
--
http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On Mon, 18 Jun 2012 02:30:50 -0700, jmfauth wrote:
> On 18 juin, 10:28, Benjamin Kaplan wrote:
>> The u prefix is only there to
>> make it easier to port a codebase from Python 2 to Python 3. It doesn't
>> actually do anything.
>
>
> It does. I shew it!
Incorrect. You are assuming that Python 3 input eval's the input like
Python 2 does. That is wrong. All you show is that the one-character
string "a" is not equal to the four-character string "u'a'", which is
hardly a surprise. You wouldn't expect the string "3" to equal the string
"int('3')" would you?
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: post init call
Am 18.06.2012 09:10 schrieb Prashant: class Shape(object): def __init__(self, shapename): self.shapename = shapename def update(self): print "update" class ColoredShape(Shape): def __init__(self, color): Shape.__init__(self, color) self.color = color print 1 print 2 print 3 self.update() User can sub-class 'Shape' and create custom shapes. How ever user must call 'self.update()' as the last argument when ever he is sub-classing 'Shape'. I would like to know if it's possible to call 'self.update()' automatically after the __init__ of sub-class is done? Cheers I would construct it this way: class Shape(object): def __init__(self, *args): self.args = args self.init() self.update() # or: if self.init(): self.update() def init(self): return False # don't call update def update(self): print "update" @propery def shapename(self): return self.args[0] class ColoredShape(Shape): def init(self): print 1, 2, 3 self.update() return True @property def color(self): return self.args[1] Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: post init call
Prashant wrote: > class Shape(object): > def __init__(self, shapename): > self.shapename = shapename > > > def update(self): > print "update" > > class ColoredShape(Shape): > def __init__(self, color): > Shape.__init__(self, color) > self.color = color > print 1 > print 2 > print 3 > self.update() > > User can sub-class 'Shape' and create custom shapes. How ever user must > call 'self.update()' as the last argument when ever he is sub-classing > 'Shape'. I would like to know if it's possible to call 'self.update()' > automatically after the __init__ of sub-class is done? I don't think so. You could however shuffle things around a bit: class Shape(object): def __init__(self, shapename, *args, **kw): self.shapename = shapename self.init(*args, **kw) self.update() def init(self, *args, **kw): pass def update(self): print "update" In that constellation you would override init(), not __init__(): class ColoredShape(Shape): def init(self, color, **kw): self.color = color print 1 print 2 print 3 -- http://mail.python.org/mailman/listinfo/python-list
Problem with ImapLib and subject in French
Hi,
I'm trying to search some mails with SUBJECT criteria, but the problem is
the encoding, I'm trying to search french terms (impalib and python V2.7)
I've tried few things, but I think the encoding is the problem, in my mail
header I have something like this:
=?iso-8859-1?Q?Job:_"Full_Backup_Les_Gr=E8ves_du_Lac")_?=
I need to search unseen mail with the FROM and the SUBJECT criteria. I take
those two in parameters in my python script and the second contain special
caracters like é or è, so I encode the string like this:
temp = header_encode(unicode('Les grèves','utf-8'),
charset='iso-8859-1')
And the string is exactly the same as the header:
=?iso-8859-1?q?Full_Backup_Les_Gr=E8ves?=
But the search function doesn't find my email, and I don't know why, even
if I try with the entire string of the subject.
I hope you can understand my question and my english (I'm from switzerland
so my english is not so good) and you can answer me.
Thanks in advance and best regards
Valentin Mercier
--
http://mail.python.org/mailman/listinfo/python-list
module name vs '.'
Am I correct that a module could never come from a file path with a '.' in the name? -- http://mail.python.org/mailman/listinfo/python-list
Re: module name vs '.'
On 06/18/2012 09:19 AM, Neal Becker wrote: > Am I correct that a module could never come from a file path with a '.' in > the > name? > No. Simple example: Create a directory called src.directory In that directory, create two files ::neal.py:: import becker print becker.__file__ print becker.hello() ::becker.py:: def hello(): print "Inside hello" return "returning" Then run neal.py, from that directory; davea@think:~/temppython/src.directory$ python neal.py /mnt/data/davea/temppython/src.directory/becker.pyc Inside hello returning davea@think:~/temppython/src.directory$ Observe the results of printing __file__ Other approaches include putting a directory path containing a period into sys.path -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: module name vs '.'
I meant a module src.directory contains __init__.py neal.py becker.py from src.directory import neal On Mon, Jun 18, 2012 at 9:44 AM, Dave Angel wrote: > On 06/18/2012 09:19 AM, Neal Becker wrote: > > Am I correct that a module could never come from a file path with a '.' > in the > > name? > > > > No. > > Simple example: Create a directory called src.directory > In that directory, create two files > > ::neal.py:: > import becker > print becker.__file__ > print becker.hello() > > > ::becker.py:: > def hello(): >print "Inside hello" >return "returning" > > > Then run neal.py, from that directory; > > > davea@think:~/temppython/src.directory$ python neal.py > /mnt/data/davea/temppython/src.directory/becker.pyc > Inside hello > returning > davea@think:~/temppython/src.directory$ > > Observe the results of printing __file__ > > Other approaches include putting a directory path containing a period > into sys.path > > > > -- > > DaveA > > -- http://mail.python.org/mailman/listinfo/python-list
Re: module name vs '.'
On 06/18/2012 09:47 AM, Neal Becker wrote: > I meant a module > > src.directory contains > __init__.py > neal.py > becker.py > > from src.directory import neal > > > On Mon, Jun 18, 2012 at 9:44 AM, Dave Angel wrote: > >> On 06/18/2012 09:19 AM, Neal Becker wrote: >>> Am I correct that a module could never come from a file path with a '.' >> in the >>> name? >>> >> >> No. >> >> Simple example: Create a directory called src.directory >> In that directory, create two files >> >> ::neal.py:: >> import becker >> print becker.__file__ >> print becker.hello() >> >> >> ::becker.py:: >> def hello(): >>print "Inside hello" >>return "returning" >> >> >> Then run neal.py, from that directory; >> >> >> davea@think:~/temppython/src.directory$ python neal.py >> /mnt/data/davea/temppython/src.directory/becker.pyc >> Inside hello >> returning >> davea@think:~/temppython/src.directory$ >> >> Observe the results of printing __file__ >> >> Other approaches include putting a directory path containing a period >> into sys.path >> >> >> >> -- >> >> DaveA >> >> > In my example, becker.py is a module and I imported it. If you're now asking specifically about using the syntax from src.directory import neal that has nothing to do with periods being in a directory name. That period in the source code separates a package name from a module name, and will not find a package named "src.directory" -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On 18 juin, 12:11, Steven D'Aprano wrote:
> On Mon, 18 Jun 2012 02:30:50 -0700, jmfauth wrote:
> > On 18 juin, 10:28, Benjamin Kaplan wrote:
> >> The u prefix is only there to
> >> make it easier to port a codebase from Python 2 to Python 3. It doesn't
> >> actually do anything.
>
> > It does. I shew it!
>
> Incorrect. You are assuming that Python 3 input eval's the input like
> Python 2 does. That is wrong. All you show is that the one-character
> string "a" is not equal to the four-character string "u'a'", which is
> hardly a surprise. You wouldn't expect the string "3" to equal the string
> "int('3')" would you?
>
> --
> Steven
A string is a string, a "piece of text", period.
I do not see why a unicode literal and an (well, I do not
know how the call it) a "normal class " should behave
differently in code source or as an answer to an input().
Should a user write two derived functions?
input_for_entering_text()
and
input_if_you_are_entering_a_text_as_litteral()
---
Side effect from the unicode litteral reintroduction.
I do not mind about this, but I expect it does
work logically and correctly. And it does not.
PS English is not my native language. I never know
to reply to an (interro)-negative sentence.
jmf
--
http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
Perhaps this will clear things up: Python 3.3.0a4 (v3.3.0a4:7c51388a3aa7, May 31 2012, 20:17:41) [MSC v.1600 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ua = u'a' >>> literal_ua = "u'a'" >>> ua == literal_ua False >>> input_ua = input() u'a' >>> input_ua "u'a'" >>> input_ua == ua False >>> input_ua == literal_ua True >>> eval_ua = eval(literal_ua) >>> eval_ua 'a' >>> eval(literal_ua) == input_ua False >>> eval(literal_ua) == ua True >>> u'a' == 'a' True >>> u'a' is 'a' True -- CPython 3.3.0a4 | Windows NT 6.1.7601.17803 -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On 06/18/2012 10:00 AM, jmfauth wrote: > > A string is a string, a "piece of text", period. I do not see why a > unicode literal and an (well, I do not know how the call it) a "normal > class " should behave differently in code source or as an answer > to an input(). Wrong. The rules for parsing source code are NOT applied in general to Python 3's input data, nor to file I/O done with methods like myfile.readline(). We do not expect the runtime code to look for def statements, nor for class statements, and not for literals. A literal is a portion of source code where there are specific rules applied, starting with the presence of some quote characters. This is true of nearly all languages, and in most languages, the difference is so obvious that the question seldom gets raised. For example, in C code a literal is evaluated at compile time, and by the time an end user sees an input prompt, he probably doesn't even have a compiler on the same machine. When an end user types in his data (into an input statement, typically), he does NOT use quote literals, he does not use hex escape codes, he does not escape things with backslash. If he wants an o with an umlaut on it, he'd better have such a character available on his keyboard. i'd suggest playing around a little with literal assignments and input statements and print functions. In those literals, try entering escape sequences (eg. "ab\x41cd") Run such programs from the command line, and observe the output from the prints. Do this without using the interactive interpreter, as by default it "helpfully" displays expressions with the repr() function, which confuses the issue. > Should a user write two derived functions? input_for_entering_text() > and input_if_you_are_entering_a_text_as_litteral() --- Side effect > from the unicode litteral reintroduction. I do not mind about this, > but I expect it does work logically and correctly. And it does not. PS > English is not my native language. I never know to reply to an > (interro)-negative sentence. jmf The user doesn't write functions, the programmer does. Until you learn to distinguish between those two phases, you'll continue having this confusion. If you (the programmer) want a function that asks the user to enter a literal at the input prompt, you'll have to write a post-processing for it, which looks for prefixes, for quotes, for backslashes, etc., and encodes the result. There very well may be such a decoder in the Python library, but input does nothing of the kind. The literal modifiers (u"" or r"") are irrelevant here. The "problem" you're having is universal, and not new. The characters in source code have different semantic meanings than those entered in input, or read from file I/O. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with ImapLib and subject in French
On 18 June 2012 12:31, Valentin Mercier wrote:
> Hi,
>
> I'm trying to search some mails with SUBJECT criteria, but the problem is
> the encoding, I'm trying to search french terms (impalib and python V2.7)
>
> I've tried few things, but I think the encoding is the problem, in my mail
> header I have something like this:
>
> =?iso-8859-1?Q?Job:_"Full_Backup_Les_Gr=E8ves_du_Lac")_?=
>
> I need to search unseen mail with the FROM and the SUBJECT criteria. I take
> those two in parameters in my python script and the second contain special
> caracters like é or è, so I encode the string like this:
>
> temp = header_encode(unicode('Les grèves','utf-8'),
> charset='iso-8859-1')
>
> And the string is exactly the same as the header:
>
> =?iso-8859-1?q?Full_Backup_Les_Gr=E8ves?=
>
> But the search function doesn't find my email, and I don't know why, even if
> I try with the entire string of the subject.
Can you post the code that doesn't work? It's hard to debug "search
function doesn't find my email". It would be easier to debug actual
code (note: I'm not a user of imaplib so I'm not promising anything :)
--
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list
Cross-platform mobile application written in Python
Hello. I would like to point you to a project that I worked on lately: iCam, a video surveillance cross-platform mobile application (Android, Symbian, iOS, WinCE) written in Python, which uploads normally media to YouTube and Picasa. The project can be found at http://code.google.com/p/icam-mobile-revival/ (also at http://go.to/slog). I would be happy to answer questions related to the project and appreciate if you can provide me feedback. With best regards, Alex Susu -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
Am 18.06.2012 16:00, schrieb jmfauth: > A string is a string, a "piece of text", period. No. There are different representations for the same piece of text even in the context of just Python. b'fou', u'fou', 'fou' are three different source code representations, resulting in two different runtime representation and they all represent the same text: fou. > I do not see why a unicode literal and an (well, I do not > know how the call it) a "normal class " should behave > differently in code source or as an answer to an input(). input() retrieves a string from a user, not from a programmer that can be expected to know the difference between b'\x81' and u'\u20ac'. > Should a user write two derived functions? > > input_for_entering_text() > and > input_if_you_are_entering_a_text_as_litteral() With "user" above, I guess you mean "Python programmer". In that case, the answer is yes. Although asking the user of your program to learn about Python's string literal formatting options is a bit much. > Side effect from the unicode litteral reintroduction. > I do not mind about this, but I expect it does > work logically and correctly. And it does not. Yes it does. The user enters something. Python receives this and provides it as string. You as a programmer are now supposed to interpret, parse etc this string according to your program logic. BTW: Just in case there is a language (native language, not programming language) problem, don't hesitate to write in your native language, too. Chances are good that someone here understands you. Good luck! Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
Thinks are very clear to me. I wrote enough interactive
interpreters with all available toolkits for Windows
since I know Python (v. 1.5.6).
I do not see why the semantic may vary differently
in code source or in an interactive interpreter,
esp. if Python allow it!
If you have to know by advance what an end user
is supposed to type and/or check it ('str' or unicode
literal) in order to know if the answer has to be
evaluated or not, then it is better to reintroduce
input() and raw_input().
jmf
--
http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On Tue, Jun 19, 2012 at 1:44 AM, jmfauth wrote: > I do not see why the semantic may vary differently > in code source or in an interactive interpreter, > esp. if Python allow it! When you're asking for input, you usually aren't looking for code. It doesn't matter about string literal formats, because you don't need to delimit it. In code, you need to make it clear to the interpreter where your string finishes, and that's traditionally done with quote characters: name = "Chris Angelico" # this isn't part of the string, because the two quotes mark off the ends of it And you can include characters in your literals that you don't want in your source code: bad_chars = "\x00\x1A\x0A"# three characters NUL, SUB, LF Everything about raw strings, Unicode literals, triple-quoted strings, etc, etc, etc, is just variants on these two basic concepts. The interpreter needs to know what you mean. With input, though, the end of the string is defined in some other way (such as by the user pushing Enter). The interpreter knows without any extra hints where it's to stop parsing. Also, there's no need to protect certain characters from getting into your code. It's a much easier job for the interpreter, which translates to being much simpler for the user: just type what you want and hit Enter. Quote characters have no meaning. Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
jmfauth writes: > Thinks are very clear to me. I wrote enough interactive > interpreters with all available toolkits for Windows >>> r = input() u'a Traceback (most recent call last): File "", line 1, in SyntaxError: u'a Er, no, not really :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On 6/18/2012 11:32 AM, Jussi Piitulainen wrote: > jmfauth writes: > >> Thinks are very clear to me. I wrote enough interactive >> interpreters with all available toolkits for Windows > r = input() > u'a > Traceback (most recent call last): > File "", line 1, in > SyntaxError: u'a > > Er, no, not really :-) > You're using 2.x; this thread concerns 3.3, which, as has been repeated several times, does not evaluate strings passed via input() like 2.x. That code does not raise a SyntaxError in 3.x. -- CPython 3.3.0a4 | Windows NT 6.1.7601.17803 -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On Monday, June 18, 2012 9:44:17 AM UTC-6, jmfauth wrote:
> Thinks are very clear to me. I wrote enough interactive
> interpreters with all available toolkits for Windows
> since I know Python (v. 1.5.6).
>
> I do not see why the semantic may vary differently
> in code source or in an interactive interpreter,
> esp. if Python allow it!
>
> If you have to know by advance what an end user
> is supposed to type and/or check it ('str' or unicode
> literal) in order to know if the answer has to be
> evaluated or not, then it is better to reintroduce
> input() and raw_input().
>
The change between Python 2.x and 3.x was made for security reasons. The
developers felt, correctly in my opinion, that the simpler operation should not
pose a security risk of a malicious user entering an expression that would
corrupt the program.
In Python 3.x the equivalent of Python 2.x's input() function is eval(input()).
It poses the same security risk: acting on unchecked user data.
John Roth
> jmf
--
http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
> If you (the programmer) want a function that asks the user to enter a > literal at the input prompt, you'll have to write a post-processing for > it, which looks for prefixes, for quotes, for backslashes, etc., and > encodes the result. There very well may be such a decoder in the Python > library, but input does nothing of the kind. As it says at the end of eval() (which you definitely don't want to use here due to side effects): See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals. DC -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
We are turning in circles. You are somehow legitimating the reintroduction of unicode literals and I shew, not to say proofed, it may be a source of problems. Typical Python desease. Introduce a problem, then discuss how to solve it, but surely and definitivly do not remove that problem. As far as I know, Python 3.2 is working very well. jmf -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On 06/18/2012 12:55 PM, Andrew Berg wrote: > On 6/18/2012 11:32 AM, Jussi Piitulainen wrote: >> jmfauth writes: >> >>> Thinks are very clear to me. I wrote enough interactive >>> interpreters with all available toolkits for Windows > r = input() >> u'a >> Traceback (most recent call last): >> File "", line 1, in >> SyntaxError: u'a >> >> Er, no, not really :-) >> > You're using 2.x; this thread concerns 3.3, which, as has been repeated > several times, does not evaluate strings passed via input() like 2.x. > That code does not raise a SyntaxError in 3.x. > And you're missing the context. jmfauth thinks we should re-introduce the input/raw-input distinction so he could parse literal strings. So Jussi demonstrated that the 2.x input did NOT satisfy fmfauth's dreams. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On 6/18/2012 12:03 PM, Dave Angel wrote: > And you're missing the context. jmfauth thinks we should re-introduce > the input/raw-input distinction so he could parse literal strings. So > Jussi demonstrated that the 2.x input did NOT satisfy fmfauth's dreams. You're right. I missed that part of jmfauth's post. -- CPython 3.3.0a4 | Windows NT 6.1.7601.17803 -- http://mail.python.org/mailman/listinfo/python-list
Re: Academic citation of Python
Ben Finney wrote: Curt writes: On 2012-06-16, Christian Heimes wrote: Actually it's "van Rossum, Guido", not "Rossum, Guido van". The "van" is part of the family name, not a middle name. It's like "da Vinci, Leonardo" or "von Sydow, Max". On one occasion Guido complained that Americans always get his name wrong. I've read that now he prefers Guido V. Rossum, Jr. Citation needed. But what format should it take? ;) ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
Andrew Berg writes: > On 6/18/2012 11:32 AM, Jussi Piitulainen wrote: > > jmfauth writes: > > > >> Thinks are very clear to me. I wrote enough interactive > >> interpreters with all available toolkits for Windows > > > r = input() > > u'a > > Traceback (most recent call last): > > File "", line 1, in > > SyntaxError: u'a > > > > Er, no, not really :-) > > > You're using 2.x; this thread concerns 3.3, which, as has been > repeated several times, does not evaluate strings passed via input() > like 2.x. That code does not raise a SyntaxError in 3.x. I used 3.1.2, and I really meant the "not really". And the ":-)". I edited out the command that raised the exception. This thread is weird. If I didn't know that things are very clear to jmfauth, I would think that the behaviour of input() that I observe has absolutely nothing to do with the u'' syntax in source code. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with ImapLib and subject in French
Valentin Mercier writes: > I'm trying to search some mails with SUBJECT criteria, but the problem is the > encoding, I'm trying to search french terms (impalib and python V2.7) > > I've tried few things, but I think the encoding is the problem, in my mail > header I have something like this: > > =?iso-8859-1?Q?Job:_"Full_Backup_Les_Gr=E8ves_du_Lac")_?= I would expect that it is the task of the IMap server to handle the header encoding on its side. Check the description of its search function how it expects its input: does it want it "header encoded" or in some other form. -- Dieter -- http://mail.python.org/mailman/listinfo/python-list
Re: Hashable object with self references OR how to create a tuple that refers to itself
Dieter Maurer wrote: > You can create a tuple in "C" and then put a reference to itself into > it, but I am quite convinced that you cannot do it in Python itself. > (Of course, you could use "cython" to generate C code with a source > language very similar to Python). I don't think you can even do it in C without breaking the specified API: PyTuple_SetItem fails if the reference count of the tuple is not 1, but it also steals the reference of the object that is being added to the tuple so if you don't increment the reference count before attempting to add the tuple to itself you've broken the rules for reference counting. -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Tkinter binding question
Hi All,
For most of an afternoon I've had that stuck-in-a-dead-end feeling
probing to no avail all permutations formulating bindings, trying to
make sense of manuals and tutorials. Here are my bindings:
label_frame.bind ('', self.color_selected)
label_frame.bind ('', self.color_selectable)
label_frame.bind ('', self.pick_record)
label_frame.bind ('', self.info_profile)
and work fine. But when I try to select an entered item,
the moment I push the left or the right button, color_selectable ()
and color_selected () are called again in rapid succession. The same
effect happens even when I push the middle mouse button which is
rather weird, because it has no binding. The behavior suggests that
no event can occur on an entered widget before it is left again and
if an event other that comes in, the callback gets
called automatically. That can't be right, though. It isn't possible
to click an item without entering it.
I put traces in all of the four callbacks. So I know what gets
called an what doesn't. Traces are:
On :
hit list.color_selected ()
On :
hit list.color_selectable ()
Fine so far.
:
hit list.color_selected ()# Still fine
or or :
hit list.color_selectable () # Not so fine!
hit list.color_selected ()
(or -2 or -3)
(nothing)
Thanks for any suggestion
Frederic
OS: Ubuntu 10.04 LTS
Python: sys.version: 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3]
Tkinter: VERSION 73770 (help (Tkinter), last line)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On 6/18/2012 12:39 PM, jmfauth wrote: We are turning in circles. You are, not we. Please stop. You are somehow legitimating the reintroduction of unicode literals We are not 'reintroducing' unicode literals. In Python 3, string literals *are* unicode literals. Other developers reintroduced a now meaningless 'u' prefix for the purpose of helping people write 2&3 code that runs on both Python 2 and Python 3. Read about it here http://python.org/dev/peps/pep-0414/ In Python 3.3, 'u' should *only* be used for that purpose and should be ignored by anyone not writing or editing 2&3 code. If you are not writing such code, ignore it. > and I shew, not to say proofed, it may be a source of problems. You are the one making it be a problem. Typical Python desease. Introduce a problem, then discuss how to solve it, but surely and definitivly do not remove that problem. The simultaneous reintroduction of 'ur', but with a different meaning than in 2.7, *was* a problem and it should be removed in the next release. As far as I know, Python 3.2 is working very well. Except that many public libraries that we would like to see ported to Python 3 have not been. The purpose of reintroducing 'u' is to encourage more porting of Python 2 code. Period. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: module name vs '.'
On 6/18/2012 9:54 AM, Dave Angel wrote:
On 06/18/2012 09:47 AM, Neal Becker wrote:
I meant a module
You are correct that using periods in a module name conflicts with
periods in import statement syntax.
from src.directory import neal
that has nothing to do with periods being in a directory name. That
period in the source code separates a package name from a module name,
and will not find a package named "src.directory"
So one would have to *not* use import statement syntax, but use lower
level facilities, such as importlib or (untested)
neal = __import__('src.directory', )
Conclusion: putting periods in the name of module files (including
directories) except for .py- extensions, is generally a bad idea.
--
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list
Checking compatibility of a script across Python versions automatically
Are there any tools out there that will parse a script and tell me if it is compatible with an arbitrary version of Python and highlight any incompatibilities? I need to check a few of my scripts that target 3.2 to see if I can make them compatible with 3.0 and 3.1 if they aren't already. I found pyqver, but it isn't accurate (at least for 3.2/3.3 scripts) and hasn't been updated in 2 years. I could look over the docs and do it manually, but one of the scripts isn't small, so I'd prefer not to. -- CPython 3.3.0a4 | Windows NT 6.1.7601.17803 -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3.3 unicode literal and input()
On Jun 18, 8:45 pm, Terry Reedy wrote: > On 6/18/2012 12:39 PM, jmfauth wrote: > > > We are turning in circles. > > You are, not we. Please stop. > > > You are somehow legitimating the reintroduction of unicode > > literals > > We are not 'reintroducing' unicode literals. In Python 3, string > literals *are* unicode literals. > > Other developers reintroduced a now meaningless 'u' prefix for the > purpose of helping people write 2&3 code that runs on both Python 2 and > Python 3. Read about it herehttp://python.org/dev/peps/pep-0414/ > > In Python 3.3, 'u' should *only* be used for that purpose and should be > ignored by anyone not writing or editing 2&3 code. If you are not > writing such code, ignore it. > > > and I shew, not to say proofed, it may > > > be a source of problems. > > You are the one making it be a problem. > > > Typical Python desease. Introduce a problem, > > then discuss how to solve it, but surely and > > definitivly do not remove that problem. > > The simultaneous reintroduction of 'ur', but with a different meaning > than in 2.7, *was* a problem and it should be removed in the next release. > > > As far as I know, Python 3.2 is working very > > well. > > Except that many public libraries that we would like to see ported to > Python 3 have not been. The purpose of reintroducing 'u' is to encourage > more porting of Python 2 code. Period. > > -- > Terry Jan Reedy It's a matter of perspective. I expected to have finally a clean Python, the goal is missed. I have nothing to object. It is "your" (core devs) project, not mine. At least, you understood my point of view. I'm a more than two decades TeX user. At the release of XeTeX (a pure unicode TeX-engine), the devs had, like Python2/3, to make anything incompatible. A success. It did not happen a week without seeing a updated package or a refreshed documentation. Luckily for me, Xe(La)TeX is more important than Python. As a scientist, Python is perfect. >From an educational point of view, I'm becoming more and more skeptical about this language, a moving target. Note that I'm not complaining, only "desappointed". jmf -- http://mail.python.org/mailman/listinfo/python-list
Re: python 3.3 bz2 decompression testing results
Hi Pauli, Thank you for your interest in improving the bz2 module. However, I'm not sure of what you are saying in your email. If you believe you have found a bug in the module, then please provide clear instructions on how to reproduce the error(s), preferably using just one data file that triggers the problem. About Valgrind and Linux, I would be happy to fix up any memory leaks you find. However, bear in mind that running CPython under Valgrind produces quite a number of warnings even without doing anything with the bz2 module, so interpreting its output will be take a substantial amount of effort. Regards, Nadeem -- http://mail.python.org/mailman/listinfo/python-list
Conditional decoration
Is there any way to conditionally apply a decorator to a function? For example, in django, I want to be able to control, via a run-time config flag, if a view gets decorated with @login_required(). @login_required() def my_view(request): pass -- http://mail.python.org/mailman/listinfo/python-list
Re: Conditional decoration
[email protected] (Roy Smith) writes: > Is there any way to conditionally apply a decorator to a function? > For example, in django, I want to be able to control, via a run-time > config flag, if a view gets decorated with @login_required(). > > @login_required() > def my_view(request): > pass You could write a decorator that takes the value of the flag and either does nothing or decorates it's target function. -- http://mail.python.org/mailman/listinfo/python-list
