C Structure rebuild with ctypes
Hi All, I need to use a library written in C. The routine "int func (int handle, int *numVars, char ***varNames, int **varTypes)" expects a complex object: " ... Variable names are structured as an array of *numVars pointers, each pointing to a char string containing a variable name, and *varNames is set to point to the first element of the array. Variable types are stored into a corresponding array of *numVars in elements, and *varTypes is set to point to the first element of the array." I tried using ctypes but nothing worked, e.g. "varNames = (c_char_p(c_char * 65) * NumberOfVariables)()" Can anyboby help? How do I have to state the structure "array of pointers to char string"? How is a pointer to the first element of such an array defined using ctypes? How do I allocate enough space for the char the array points to? Best regards Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: C Structure rebuild with ctypes
Hi Mark,
many thanks for your help. I tried your code in my program and it worked.
I would like to understand what the code is doing and I have some questions
to it.
> Are you passing in these values, or are they being returned? To me the
> depth of the pointer references implies numVars, varNames, and varTypes
> are out parameters. I'll assume that for now. If they are in/out
> parameters let me know.
Your exactly right: the parameters numVars, varNames and VarTypes are out
paramters.
> I mocked up a DLL to test returning values of these types. I used VS2008
> and compiled with "cl /LD func.c":
>
> --- func.c ---
> #include
> #define FUNCDLL
> #include "func.h"
>
> static char* g_data[] = {"one","two","three"};
> static int g_types[] = {1,2,3};
>
> FUNCAPI int func (int handle, int *numVars, char ***varNames, int
> **varTypes)
> {
> *numVars = _countof(g_data);
> *varNames = g_data;
> *varTypes = g_types;
> return handle + 1;
> }
What does the signature FUNCAPI do in this context?
>
>
> --- func.h ---
> #ifdef FUNCDLL
> #define FUNCAPI __declspec(dllexport)
> #else
> #define FUNCAPI __declspec(dllimport)
> #endif
>
> FUNCAPI int func (int handle, int *numVars, char ***varNames, int
> **varTypes);
>
Do I need to wrap the compiled DLL file this way? I can load the DLL with
the CDLL method, make calls to simple functions, e.g. no parameters,
returning stirng and get the right values.
I added all the code from your func.py module to the code I already had.
And -- it works fine and delivers the expected results.
> --- func.py ---
... cut ...
>
> # int func (int handle, int *numVars, char ***varNames, int **varTypes)
> func = c.CDLL('func').func
> func.restype = INT
> func.argtypes = [INT,PINT,PPPCHAR,PPINT]
I added this part to my program.
> # allocate storage for the out parameters
> numVars = INT()
> varNames = PPCHAR()
> varTypes = PINT()
I added this part also.
> print func(5,c.byref(numVars),c.byref(varNames),c.byref(varTypes))
I called the library routine.
> # numVars contains size of returned arrays. Recast to access.
> varNamesArray = c.cast(varNames,c.POINTER(PCHAR * numVars.value))
> varTypesArray = c.cast(varTypes,c.POINTER(INT * numVars.value))
What does this cast? How do I know how I have to cast the objects returned
from the library function?
What kind of objects do I get? I learned that the values of objects created
by the ctypes module are accessed using object.value?
Best regards
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: C Structure rebuild with ctypes
Hi Mark, many thanks for your valuable help. >>> # numVars contains size of returned arrays. Recast to access. >>> varNamesArray = c.cast(varNames,c.POINTER(PCHAR * numVars.value)) >>> varTypesArray = c.cast(varTypes,c.POINTER(INT * numVars.value)) One last question: You created an object varNamesArray as an ctypes array. This object has a method "contents". How do I find out what other methods this objects has? For instance a method to retrieve the size of the array? Is this documented somewhere? Best regards Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: C Structure rebuild with ctypes
Hi Mark, > Are you passing in these values, or are they being returned? To me the > depth of the pointer references implies numVars, varNames, and varTypes > are out parameters. I'll assume that for now. If they are in/out > parameters let me know. If these parameters were in parameters. What would I have to do different? Best regards Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: C Structure rebuild with ctypes
Hi Mark,
many thanks for your hints.
> --- func.py --
> import ctypes as c
>
> # int func (int numVars, char **varNames, int *varTypes)
>
> INT = c.c_int
> PINT = c.POINTER(INT)
> PCHAR = c.c_char_p
> PPCHAR = c.POINTER(PCHAR)
>
> func = c.CDLL('func').func
> func.restype = None
> func.argtypes = [INT,PPCHAR,PINT]
>
> numVars = 3
> varNames = (PCHAR * numVars)('abc','def','ghi')
> varTypes = (INT * numVars)(1,2,3)
>
> func(numVars,varNames,varTypes)
The function to call has the following signiture:
int SetVarLabel(int handle, const char *varName, const char *varLabel)
I did as you suggested by doing the following:
INT = c_int
PCHAR = c_char_p
libc.argtypes = [INT,PCHAR,PCHAR]
vn = create_string_buffer("var1")
vl = create_string_buffer("Label")
print "vn: ", vn.value
print "vl: ", vl.value
returnCode = libc.SetVarLabel(h,byref(vn), byref(vl))
print "Return Code: ", returnCode
The return code is always "variable not found". Thus my call to the C
library is not working.
What do I do wrong?
Best regards
Georg
--
http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.2.5 and Python 3.3.2
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I am pleased to announce the releases of Python 3.2.5 and 3.3.2. The releases fix a few regressions in 3.2.4 and 3.3.1 in the zipfile, gzip and xml.sax modules. Details can be found in the changelogs: http://hg.python.org/cpython/file/v3.2.5/Misc/NEWS and http://hg.python.org/cpython/file/v3.3.2/Misc/NEWS To download Python 3.2.5 or Python 3.3.2, visit: http://www.python.org/download/releases/3.2.5/ or http://www.python.org/download/releases/3.3.2/ respectively. As always, please report bugs to http://bugs.python.org/ (Thank you to those who reported these regressions.) Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and all contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.19 (GNU/Linux) iEYEARECAAYFAlGUbJ4ACgkQN9GcIYhpnLDH8ACdEM4k7bobLJsFmCb49zuwQR3W EjgAoIWAOFNhJNdTAWEGSWqFWUP20wrb =YnPr -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.0 beta 1
On behalf of the Python development team, I'm happy to announce the
first beta release of Python 3.3.0.
This is a preview release, and its use is not recommended in
production settings.
Python 3.3 includes a range of improvements of the 3.x series, as well
as easier porting between 2.x and 3.x. Major new features and changes
in the 3.3 release series are:
* PEP 380, syntax for delegating to a subgenerator ("yield from")
* PEP 393, flexible string representation (doing away with the
distinction between "wide" and "narrow" Unicode builds)
* A C implementation of the "decimal" module, with up to 80x speedup
for decimal-heavy applications
* The import system (__import__) now based on importlib by default
* The new "lzma" module with LZMA/XZ support
* PEP 397, a Python launcher for Windows
* PEP 405, virtual environment support in core
* PEP 420, namespace package support
* PEP 3151, reworking the OS and IO exception hierarchy
* PEP 3155, qualified name for classes and functions
* PEP 409, suppressing exception context
* PEP 414, explicit Unicode literals to help with porting
* PEP 418, extended platform-independent clocks in the "time" module
* PEP 412, a new key-sharing dictionary implementation that
significantly saves memory for object-oriented code
* PEP 362, the function-signature object
* The new "faulthandler" module that helps diagnosing crashes
* The new "unittest.mock" module
* The new "ipaddress" module
* The "sys.implementation" attribute
* A policy framework for the email package, with a provisional (see
PEP 411) policy that adds much improved unicode support for email
header parsing
* A "collections.ChainMap" class for linking mappings to a single unit
* Wrappers for many more POSIX functions in the "os" and "signal"
modules, as well as other useful functions such as "sendfile()"
* Hash randomization, introduced in earlier bugfix releases, is now
switched on by default
In total, almost 500 API items are new or improved in Python 3.3.
For a more extensive list of changes in 3.3.0, see
http://docs.python.org/3.3/whatsnew/3.3.html (*)
To download Python 3.3.0 visit:
http://www.python.org/download/releases/3.3.0/
Please consider trying Python 3.3.0 with your code and reporting any bugs
you may notice to:
http://bugs.python.org/
Enjoy!
(*) Please note that this document is usually finalized late in the release
cycle and therefore may have stubs and missing entries at this point.
--
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
--
http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.0 beta 2
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
On behalf of the Python development team, I'm happy to announce the
second beta release of Python 3.3.0 -- a little later than originally
scheduled, but much better for it.
This is a preview release, and its use is not recommended in
production settings.
Python 3.3 includes a range of improvements of the 3.x series, as well
as easier porting between 2.x and 3.x. Major new features and changes
in the 3.3 release series are:
* PEP 380, syntax for delegating to a subgenerator ("yield from")
* PEP 393, flexible string representation (doing away with the
distinction between "wide" and "narrow" Unicode builds)
* A C implementation of the "decimal" module, with up to 80x speedup
for decimal-heavy applications
* The import system (__import__) now based on importlib by default
* The new "lzma" module with LZMA/XZ support
* PEP 397, a Python launcher for Windows
* PEP 405, virtual environment support in core
* PEP 420, namespace package support
* PEP 3151, reworking the OS and IO exception hierarchy
* PEP 3155, qualified name for classes and functions
* PEP 409, suppressing exception context
* PEP 414, explicit Unicode literals to help with porting
* PEP 418, extended platform-independent clocks in the "time" module
* PEP 412, a new key-sharing dictionary implementation that
significantly saves memory for object-oriented code
* PEP 362, the function-signature object
* The new "faulthandler" module that helps diagnosing crashes
* The new "unittest.mock" module
* The new "ipaddress" module
* The "sys.implementation" attribute
* A policy framework for the email package, with a provisional (see
PEP 411) policy that adds much improved unicode support for email
header parsing
* A "collections.ChainMap" class for linking mappings to a single unit
* Wrappers for many more POSIX functions in the "os" and "signal"
modules, as well as other useful functions such as "sendfile()"
* Hash randomization, introduced in earlier bugfix releases, is now
switched on by default
In total, almost 500 API items are new or improved in Python 3.3.
For a more extensive list of changes in 3.3.0, see
http://docs.python.org/3.3/whatsnew/3.3.html (*)
To download Python 3.3.0 visit:
http://www.python.org/download/releases/3.3.0/
Please consider trying Python 3.3.0 with your code and reporting any bugs
you may notice to:
http://bugs.python.org/
Enjoy!
(*) Please note that this document is usually finalized late in the release
cycle and therefore may have stubs and missing entries at this point.
- --
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.19 (GNU/Linux)
iEYEARECAAYFAlAnxVAACgkQN9GcIYhpnLAECACcDeE+N2AfYVnuwMkq682znfDU
ODAAn0J87+MVA9WHEV5iYZd3ub9ZhbpC
=LvY0
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.0 release candidate 1
On behalf of the Python development team, I'm delighted to announce the
first release candidate of Python 3.3.0.
This is a preview release, and its use is not recommended in
production settings.
Python 3.3 includes a range of improvements of the 3.x series, as well
as easier porting between 2.x and 3.x. Major new features and changes
in the 3.3 release series are:
* PEP 380, syntax for delegating to a subgenerator ("yield from")
* PEP 393, flexible string representation (doing away with the
distinction between "wide" and "narrow" Unicode builds)
* A C implementation of the "decimal" module, with up to 80x speedup
for decimal-heavy applications
* The import system (__import__) now based on importlib by default
* The new "lzma" module with LZMA/XZ support
* PEP 397, a Python launcher for Windows
* PEP 405, virtual environment support in core
* PEP 420, namespace package support
* PEP 3151, reworking the OS and IO exception hierarchy
* PEP 3155, qualified name for classes and functions
* PEP 409, suppressing exception context
* PEP 414, explicit Unicode literals to help with porting
* PEP 418, extended platform-independent clocks in the "time" module
* PEP 412, a new key-sharing dictionary implementation that
significantly saves memory for object-oriented code
* PEP 362, the function-signature object
* The new "faulthandler" module that helps diagnosing crashes
* The new "unittest.mock" module
* The new "ipaddress" module
* The "sys.implementation" attribute
* A policy framework for the email package, with a provisional (see
PEP 411) policy that adds much improved unicode support for email
header parsing
* A "collections.ChainMap" class for linking mappings to a single unit
* Wrappers for many more POSIX functions in the "os" and "signal"
modules, as well as other useful functions such as "sendfile()"
* Hash randomization, introduced in earlier bugfix releases, is now
switched on by default
In total, almost 500 API items are new or improved in Python 3.3.
For a more extensive list of changes in 3.3.0, see
http://docs.python.org/3.3/whatsnew/3.3.html
To download Python 3.3.0 visit:
http://www.python.org/download/releases/3.3.0/
Please consider trying Python 3.3.0 with your code and reporting any bugs
you may notice to:
http://bugs.python.org/
Enjoy!
--
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
--
http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.0 release candidate 2
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
On behalf of the Python development team, I'm delighted to announce the
second release candidate of Python 3.3.0.
This is a preview release, and its use is not recommended in
production settings.
Python 3.3 includes a range of improvements of the 3.x series, as well
as easier porting between 2.x and 3.x. Major new features and changes
in the 3.3 release series are:
* PEP 380, syntax for delegating to a subgenerator ("yield from")
* PEP 393, flexible string representation (doing away with the
distinction between "wide" and "narrow" Unicode builds)
* A C implementation of the "decimal" module, with up to 80x speedup
for decimal-heavy applications
* The import system (__import__) now based on importlib by default
* The new "lzma" module with LZMA/XZ support
* PEP 397, a Python launcher for Windows
* PEP 405, virtual environment support in core
* PEP 420, namespace package support
* PEP 3151, reworking the OS and IO exception hierarchy
* PEP 3155, qualified name for classes and functions
* PEP 409, suppressing exception context
* PEP 414, explicit Unicode literals to help with porting
* PEP 418, extended platform-independent clocks in the "time" module
* PEP 412, a new key-sharing dictionary implementation that
significantly saves memory for object-oriented code
* PEP 362, the function-signature object
* The new "faulthandler" module that helps diagnosing crashes
* The new "unittest.mock" module
* The new "ipaddress" module
* The "sys.implementation" attribute
* A policy framework for the email package, with a provisional (see
PEP 411) policy that adds much improved unicode support for email
header parsing
* A "collections.ChainMap" class for linking mappings to a single unit
* Wrappers for many more POSIX functions in the "os" and "signal"
modules, as well as other useful functions such as "sendfile()"
* Hash randomization, introduced in earlier bugfix releases, is now
switched on by default
In total, almost 500 API items are new or improved in Python 3.3.
For a more extensive list of changes in 3.3.0, see
http://docs.python.org/3.3/whatsnew/3.3.html
To download Python 3.3.0 visit:
http://www.python.org/download/releases/3.3.0/
Please consider trying Python 3.3.0 with your code and reporting any bugs
you may notice to:
http://bugs.python.org/
Enjoy!
- --
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.19 (GNU/Linux)
iEYEARECAAYFAlBMYJMACgkQN9GcIYhpnLCc5ACfcufn57tkNBPFU7qCpZ74GzjW
msMAn3sIwWHLdqixypnnyMBOw1ijILjo
=+e0e
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.0 release candidate 3
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
On behalf of the Python development team, I'm delighted to announce the
third release candidate of Python 3.3.0.
This is a preview release, and its use is not recommended in
production settings.
Python 3.3 includes a range of improvements of the 3.x series, as well
as easier porting between 2.x and 3.x. Major new features and changes
in the 3.3 release series are:
* PEP 380, syntax for delegating to a subgenerator ("yield from")
* PEP 393, flexible string representation (doing away with the
distinction between "wide" and "narrow" Unicode builds)
* A C implementation of the "decimal" module, with up to 80x speedup
for decimal-heavy applications
* The import system (__import__) now based on importlib by default
* The new "lzma" module with LZMA/XZ support
* PEP 397, a Python launcher for Windows
* PEP 405, virtual environment support in core
* PEP 420, namespace package support
* PEP 3151, reworking the OS and IO exception hierarchy
* PEP 3155, qualified name for classes and functions
* PEP 409, suppressing exception context
* PEP 414, explicit Unicode literals to help with porting
* PEP 418, extended platform-independent clocks in the "time" module
* PEP 412, a new key-sharing dictionary implementation that
significantly saves memory for object-oriented code
* PEP 362, the function-signature object
* The new "faulthandler" module that helps diagnosing crashes
* The new "unittest.mock" module
* The new "ipaddress" module
* The "sys.implementation" attribute
* A policy framework for the email package, with a provisional (see
PEP 411) policy that adds much improved unicode support for email
header parsing
* A "collections.ChainMap" class for linking mappings to a single unit
* Wrappers for many more POSIX functions in the "os" and "signal"
modules, as well as other useful functions such as "sendfile()"
* Hash randomization, introduced in earlier bugfix releases, is now
switched on by default
In total, almost 500 API items are new or improved in Python 3.3.
For a more extensive list of changes in 3.3.0, see
http://docs.python.org/3.3/whatsnew/3.3.html
To download Python 3.3.0 visit:
http://www.python.org/download/releases/3.3.0/
Please consider trying Python 3.3.0 with your code and reporting any bugs
you may notice to:
http://bugs.python.org/
Enjoy!
- --
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.19 (GNU/Linux)
iEYEARECAAYFAlBf+0cACgkQN9GcIYhpnLBqfgCglbN63XUr2m4Ya4ff8Hza1Axl
SgMAniQZRJi8uYfeqltf5/G4QV/+SdWT
=KXTo
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.0
On behalf of the Python development team, I'm delighted to announce the
Python 3.3.0 final release.
Python 3.3 includes a range of improvements of the 3.x series, as well
as easier porting between 2.x and 3.x. Major new features and changes
in the 3.3 release series are:
* PEP 380, syntax for delegating to a subgenerator ("yield from")
* PEP 393, flexible string representation (doing away with the
distinction between "wide" and "narrow" Unicode builds)
* A C implementation of the "decimal" module, with up to 120x speedup
for decimal-heavy applications
* The import system (__import__) now based on importlib by default
* The new "lzma" module with LZMA/XZ support
* PEP 397, a Python launcher for Windows
* PEP 405, virtual environment support in core
* PEP 420, namespace package support
* PEP 3151, reworking the OS and IO exception hierarchy
* PEP 3155, qualified name for classes and functions
* PEP 409, suppressing exception context
* PEP 414, explicit Unicode literals to help with porting
* PEP 418, extended platform-independent clocks in the "time" module
* PEP 412, a new key-sharing dictionary implementation that
significantly saves memory for object-oriented code
* PEP 362, the function-signature object
* The new "faulthandler" module that helps diagnosing crashes
* The new "unittest.mock" module
* The new "ipaddress" module
* The "sys.implementation" attribute
* A policy framework for the email package, with a provisional (see
PEP 411) policy that adds much improved unicode support for email
header parsing
* A "collections.ChainMap" class for linking mappings to a single unit
* Wrappers for many more POSIX functions in the "os" and "signal"
modules, as well as other useful functions such as "sendfile()"
* Hash randomization, introduced in earlier bugfix releases, is now
switched on by default
In total, almost 500 API items are new or improved in Python 3.3.
For a more extensive list of changes in 3.3.0, see
http://docs.python.org/3.3/whatsnew/3.3.html
To download Python 3.3.0 visit:
http://www.python.org/download/releases/3.3.0/
This is a production release, please report any bugs to
http://bugs.python.org/
Enjoy!
--
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
--
http://mail.python.org/mailman/listinfo/python-list
Re: [RELEASED] Python 3.3.0
On 09/29/2012 06:53 PM, Antoine Pitrou wrote: Hello, I've created a 3.3 category on the buildbots: http://buildbot.python.org/3.3/ http://buildbot.python.org/3.3.stable/ Someone will have to update the following HTML page: http://python.org/dev/buildbot/ Should be done now. Georg -- http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.0 alpha 1
On behalf of the Python development team, I'm happy to announce the
first alpha release of Python 3.3.0.
This is a preview release, and its use is not recommended in
production settings.
Python 3.3 includes a range of improvements of the 3.x series, as well as easier
porting between 2.x and 3.x. Major new features in the 3.3 release series are:
* PEP 380, Syntax for Delegating to a Subgenerator ("yield from")
* PEP 393, Flexible String Representation (doing away with the
distinction between "wide" and "narrow" Unicode builds)
* PEP 409, Suppressing Exception Context
* PEP 3151, Reworking the OS and IO exception hierarchy
* The new "packaging" module, building upon the "distribute" and
"distutils2" projects and deprecating "distutils"
* The new "lzma" module with LZMA/XZ support
* PEP 3155, Qualified name for classes and functions
* PEP 414, explicit Unicode literals to help with porting
* The new "faulthandler" module that helps diagnosing crashes
* Wrappers for many more POSIX functions in the "os" and "signal"
modules, as well as other useful functions such as "sendfile()"
For a more extensive list of changes in 3.3.0, see
http://docs.python.org/3.3/whatsnew/3.3.html
To download Python 3.3.0 visit:
http://www.python.org/download/releases/3.3.0/
Please consider trying Python 3.3.0a1 with your code and reporting any
bugs you may notice to:
http://bugs.python.org/
Enjoy!
--
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
--
http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.0 alpha 1
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
On behalf of the Python development team, I'm happy to announce the
second alpha release of Python 3.3.0.
This is a preview release, and its use is not recommended in
production settings.
Python 3.3 includes a range of improvements of the 3.x series, as well
as easier porting between 2.x and 3.x. Major new features and changes
in the 3.3 release series are:
* PEP 380, Syntax for Delegating to a Subgenerator ("yield from")
* PEP 393, Flexible String Representation (doing away with the
distinction between "wide" and "narrow" Unicode builds)
* PEP 409, Suppressing Exception Context
* PEP 3151, Reworking the OS and IO exception hierarchy
* A C implementation of the "decimal" module, with up to 80x speedup
for decimal-heavy applications
* The new "packaging" module, building upon the "distribute" and
"distutils2" projects and deprecating "distutils"
* The new "lzma" module with LZMA/XZ support
* PEP 3155, Qualified name for classes and functions
* PEP 414, explicit Unicode literals to help with porting
* The new "faulthandler" module that helps diagnosing crashes
* Wrappers for many more POSIX functions in the "os" and "signal"
modules, as well as other useful functions such as "sendfile()"
* Hash randomization, introduced in earlier bugfix releases, is now
switched on by default.
For a more extensive list of changes in 3.3.0, see
http://docs.python.org/3.3/whatsnew/3.3.html (*)
To download Python 3.3.0 visit:
http://www.python.org/download/releases/3.3.0/
Please consider trying Python 3.3.0 with your code and reporting any bugs
you may notice to:
http://bugs.python.org/
Enjoy!
(*) Please note that this document is usually finalized late in the release
cycle and therefore may have stubs and missing entries at this point.
- --
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.19 (GNU/Linux)
iEYEARECAAYFAk95PJgACgkQN9GcIYhpnLCN1QCfeYWp+QbPGYhaLSxc4YKnlE/F
zU8An2q5qzvjL0qaxqaYleFGoGKPzzJu
=qo4v
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.0 alpha 2
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
- -BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
On behalf of the Python development team, I'm happy to announce the
second alpha release of Python 3.3.0.
This is a preview release, and its use is not recommended in
production settings.
Python 3.3 includes a range of improvements of the 3.x series, as well
as easier porting between 2.x and 3.x. Major new features and changes
in the 3.3 release series are:
* PEP 380, Syntax for Delegating to a Subgenerator ("yield from")
* PEP 393, Flexible String Representation (doing away with the
distinction between "wide" and "narrow" Unicode builds)
* PEP 409, Suppressing Exception Context
* PEP 3151, Reworking the OS and IO exception hierarchy
* A C implementation of the "decimal" module, with up to 80x speedup
for decimal-heavy applications
* The new "packaging" module, building upon the "distribute" and
"distutils2" projects and deprecating "distutils"
* The new "lzma" module with LZMA/XZ support
* PEP 3155, Qualified name for classes and functions
* PEP 414, explicit Unicode literals to help with porting
* The new "faulthandler" module that helps diagnosing crashes
* Wrappers for many more POSIX functions in the "os" and "signal"
modules, as well as other useful functions such as "sendfile()"
* Hash randomization, introduced in earlier bugfix releases, is now
switched on by default.
For a more extensive list of changes in 3.3.0, see
http://docs.python.org/3.3/whatsnew/3.3.html (*)
To download Python 3.3.0 visit:
http://www.python.org/download/releases/3.3.0/
Please consider trying Python 3.3.0 with your code and reporting any bugs
you may notice to:
http://bugs.python.org/
Enjoy!
(*) Please note that this document is usually finalized late in the release
cycle and therefore may have stubs and missing entries at this point.
- - --
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
- -BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.19 (GNU/Linux)
iEYEARECAAYFAk95PJgACgkQN9GcIYhpnLCN1QCfeYWp+QbPGYhaLSxc4YKnlE/F
zU8An2q5qzvjL0qaxqaYleFGoGKPzzJu
=qo4v
- -END PGP SIGNATURE-
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.19 (GNU/Linux)
iEYEARECAAYFAk95P10ACgkQN9GcIYhpnLBo8QCePW2BuTqXSmtVl6/Yae1HWrGB
UFgAn0ytSqd70vq58gj9N8xUtKC+BJ2D
=3DA/
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.0 alpha 3
On behalf of the Python development team, I'm happy to announce the
third alpha release of Python 3.3.0.
This is a preview release, and its use is not recommended in
production settings.
Python 3.3 includes a range of improvements of the 3.x series, as well
as easier porting between 2.x and 3.x. Major new features and changes
in the 3.3 release series are:
* PEP 380, Syntax for Delegating to a Subgenerator ("yield from")
* PEP 393, Flexible String Representation (doing away with the
distinction between "wide" and "narrow" Unicode builds)
* PEP 409, Suppressing Exception Context
* PEP 3151, Reworking the OS and IO exception hierarchy
* A C implementation of the "decimal" module, with up to 80x speedup
for decimal-heavy applications
* The import system (__import__) is based on importlib by default
* The new "packaging" module, building upon the "distribute" and
"distutils2" projects and deprecating "distutils"
* The new "lzma" module with LZMA/XZ support
* PEP 3155, Qualified name for classes and functions
* PEP 414, explicit Unicode literals to help with porting
* PEP 418, extended platform-independent clocks in the "time" module
* The new "faulthandler" module that helps diagnosing crashes
* A "collections.ChainMap" class for linking mappings to a single unit
* Wrappers for many more POSIX functions in the "os" and "signal"
modules, as well as other useful functions such as "sendfile()"
* Hash randomization, introduced in earlier bugfix releases, is now
switched on by default
For a more extensive list of changes in 3.3.0, see
http://docs.python.org/3.3/whatsnew/3.3.html (*)
To download Python 3.3.0 visit:
http://www.python.org/download/releases/3.3.0/
Please consider trying Python 3.3.0 with your code and reporting any bugs
you may notice to:
http://bugs.python.org/
Enjoy!
(*) Please note that this document is usually finalized late in the release
cycle and therefore may have stubs and missing entries at this point.
--
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
--
http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.0 alpha 4
On behalf of the Python development team, I'm happy to announce the
fourth alpha release of Python 3.3.0.
This is a preview release, and its use is not recommended in
production settings.
Python 3.3 includes a range of improvements of the 3.x series, as well
as easier porting between 2.x and 3.x. Major new features and changes
in the 3.3 release series are:
* PEP 380, syntax for delegating to a subgenerator ("yield from")
* PEP 393, flexible string representation (doing away with the
distinction between "wide" and "narrow" Unicode builds)
* A C implementation of the "decimal" module, with up to 80x speedup
for decimal-heavy applications
* The import system (__import__) is based on importlib by default
* The new "packaging" module (also known as distutils2, and released
standalone under this name), implementing the new packaging formats
and deprecating "distutils"
* The new "lzma" module with LZMA/XZ support
* PEP 405, virtual environment support in core
* PEP 420, namespace package support
* PEP 3151, reworking the OS and IO exception hierarchy
* PEP 3155, qualified name for classes and functions
* PEP 409, suppressing exception context
* PEP 414, explicit Unicode literals to help with porting
* PEP 418, extended platform-independent clocks in the "time" module
* PEP 412, a new key-sharing dictionary implementation that
significantly saves memory for object-oriented code
* The new "faulthandler" module that helps diagnosing crashes
* The new "unittest.mock" module
* The new "ipaddress" module
* A "collections.ChainMap" class for linking mappings to a single unit
* Wrappers for many more POSIX functions in the "os" and "signal"
modules, as well as other useful functions such as "sendfile()"
* Hash randomization, introduced in earlier bugfix releases, is now
switched on by default
For a more extensive list of changes in 3.3.0, see
http://docs.python.org/3.3/whatsnew/3.3.html (*)
To download Python 3.3.0 visit:
http://www.python.org/download/releases/3.3.0/
Please consider trying Python 3.3.0 with your code and reporting any bugs
you may notice to:
http://bugs.python.org/
Enjoy!
(*) Please note that this document is usually finalized late in the release
cycle and therefore may have stubs and missing entries at this point.
--
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
--
http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.2.1 rc 2
On behalf of the Python development team, I am pleased to announce the second release candidate of Python 3.2.1. Python 3.2.1 will the first bugfix release for Python 3.2, fixing over 120 bugs and regressions in Python 3.2. For an extensive list of changes and features in the 3.2 line, see http://docs.python.org/3.2/whatsnew/3.2.html To download Python 3.2.1 visit: http://www.python.org/download/releases/3.2.1/ This is a testing release: Please consider trying Python 3.2.1 with your code and reporting any bugs you may notice to: http://bugs.python.org/ Enjoy! -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.2's contributors) -- http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.2.1
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I am pleased to announce the final release of Python 3.2.1. Python 3.2.1 is the first bugfix release for Python 3.2, fixing over 120 bugs and regressions in Python 3.2. For an extensive list of changes and features in the 3.2 line, see http://docs.python.org/3.2/whatsnew/3.2.html To download Python 3.2.1 visit: http://www.python.org/download/releases/3.2.1/ This is a final release: Please report any bugs you may notice to: http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.2's contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.17 (GNU/Linux) iEYEARECAAYFAk4aiNMACgkQN9GcIYhpnLDofwCglfgDQ1/B/TxxwfqtDxK13ksz micAn0CVWmNNaYE2a6z0N7+Dz+hCZSj1 =7Mia -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.2.2
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I'm happy to announce the Python 3.2.2 maintenance release. Python 3.2.2 mainly fixes `a regression <http://bugs.python.org/12576>`_ in the ``urllib.request`` module that prevented opening many HTTP resources correctly with Python 3.2.1. Python 3.2 is a continuation of the efforts to improve and stabilize the Python 3.x line. Since the final release of Python 2.7, the 2.x line will only receive bugfixes, and new features are developed for 3.x only. Since PEP 3003, the Moratorium on Language Changes, is in effect, there are no changes in Python's syntax and built-in types in Python 3.2. Development efforts concentrated on the standard library and support for porting code to Python 3. Highlights are: * numerous improvements to the unittest module * PEP 3147, support for .pyc repository directories * PEP 3149, support for version tagged dynamic libraries * PEP 3148, a new futures library for concurrent programming * PEP 384, a stable ABI for extension modules * PEP 391, dictionary-based logging configuration * an overhauled GIL implementation that reduces contention * an extended email package that handles bytes messages * a much improved ssl module with support for SSL contexts and certificate hostname matching * a sysconfig module to access configuration information * additions to the shutil module, among them archive file support * many enhancements to configparser, among them mapping protocol support * improvements to pdb, the Python debugger * countless fixes regarding bytes/string issues; among them full support for a bytes environment (filenames, environment variables) * many consistency and behavior fixes for numeric operations For a more extensive list of changes in 3.2, see http://docs.python.org/3.2/whatsnew/3.2.html To download Python 3.2 visit: http://www.python.org/download/releases/3.2/ Please consider trying Python 3.2 with your code and reporting any bugs you may notice to: http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.2's contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.18 (GNU/Linux) iEYEARECAAYFAk5j3d4ACgkQN9GcIYhpnLA2BACeLZ8nSdVOoxlJw4DnbM42neeA fwAAoKTHetXsVxrEfvCWSorUhoJ083kZ =5Wm1 -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.2.1 rc 1
On behalf of the Python development team, I am pleased to announce the first release candidate of Python 3.2.1. Python 3.2.1 will the first bugfix release for Python 3.2, fixing over 120 bugs and regressions in Python 3.2. For an extensive list of changes and features in the 3.2 line, see http://docs.python.org/3.2/whatsnew/3.2.html To download Python 3.2.1 visit: http://www.python.org/download/releases/3.2.1/ This is a testing release: Please consider trying Python 3.2.1 with your code and reporting any bugs you may notice to: http://bugs.python.org/ Enjoy! -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.2's contributors) -- http://mail.python.org/mailman/listinfo/python-list
x-plat gui development question Mac OS X
Hello everybody, I have recently started tinkering about with Python. If there are any Macintosh-based Python developers reading this newsgroup I would like to ask them one Macintosh-specific question: If you want to write GUI scripts on the Mac, say with Tkinter, you need to invoke "pythonw" instead of "python" and use "#! /usr/bin/pythonw" for a shebang line in your saved scripts. Of course, although a tiny problem, it is still less than welcome for cross-platform development. As one obvious workaround, would it cause any problems if I would link "/usr/bin/python/" to "/usr/bin/pythonw" instead of "/usr/bin/python2.3" (in other words I would always be using "pythonw", even for non-GUI scripts) ? So far I can't tell any difference in the interactive mode - invoking "pythonw" for non-GUI work seems to work just fine. I am not sure though if there are any system processes, say during boot-up, that depend on "python" pointing to the original location, or if there could be problems with more complex code than "Hello world". Any insights welcome Georg -- http://mail.python.org/mailman/listinfo/python-list
Help on project, anyone?
Hello, to train my Python skills I am looking for some project I can contribute to. I learned Python about one year ago, and had already some programming background behind (I contributed to SharpDevelop for instance), so I'm not the complete newbie. About myself: I'm a 20 year old German with strong interests in programming and, of course, especially in Python (I love it...). Does anyone run, or participate in, a project looking for fellow programmers? I don't have a special area of interest, well, perhaps web programming... Thanks, Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: finding name of instances created
Michael Tobis wrote:
> I have a similar problem. Here's what I do:
>
> .def new_robot_named(name,indict=globals()):
> . execstr = name + " = robot('" + name + "')"
> . exec(execstr,indict)
>
> .class robot(object):
> . def __init__(self,name):
> . self.name = name
>
> . def sayhi(self):
> . print "Hi! I'm %s!" % self.name
>
> .if __name__=="__main__":
> . new_robot_named('Bert')
> . new_robot_named('Ernie')
> . Ernie.sayhi()
> . Bert.sayhi()
Uh. Try explaining this to newbies... ;)
On a second thought, the idea is quite usable considering some differences:
class Robot(object):
# as above
class Robots(dict):
def new(self, name):
new_robot = Robot(name)
self[name] = new_robot
return new_robot
def __getattr__(self, name):
if name in self:
return self[name]
raise AttributeError
robots = Robots()
robots.new('Bert')
robots.new('Ernie')
robots.Bert.sayhi()
robots["Bert"].sayhi()
for robot in robots:
robot.sayhi()
... etc ...
This doesn't include ugly globals() and exec "tricks".
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: What is print? A function?
Roy Smith wrote: >> So I wonder, what _is_ exactly the print statement? The untraditional way of >> invoking it(without paranteses) makes me wonder. > > It's a statement, just like "write" in Fortran. When C came around, the > idea of a language having no built-in print statement and having to call > a function to generate output was "untraditional". The function was > named "printf" (with an "f" at the end) to emphasize that it was a > function call, not a built-in language keyword. I beg to differ. Doesn't 'printf' stand for 'PRINT Formatted string'? > Java, and many other > quasi-C-based languages also use print functions, and this has become so > common that people have come to expect it. It's even a function in > Perl, although that language's devil-may-care attitude about punctuation > makes it difficult to tell for sure :-) And it should have been and perhaps will be a function in Python, see "Python Regrets" by GvR. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb - Tuples
Andy Dustman wrote:
> #33
> #! /usr/bin/env python
> import MySQLdb
> db=MySQLdb.connect(host='localhost', db='photum_0_6_2', user='root',
> passwd='thkhgfgd')
> c=db.cursor()
> c.execute('select person from persons order by person')
> for (person,) in c: # or c.fetchall() (may be more portable)
> print person
>
>
> If you return more than one column, then you don't need the parentheses
> for the tuple unpacking.
You don't need the parentheses for one element either:
for person, in c:
print person
works perfectly. Note the trailing comma.
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: mounting a filesystem?
Dan Stromberg wrote: > Is there a python module that can mount a filesystem? > > More specifically, a loopback filesystem with a particular offset, under > linux? Why don't you just call the mount command via os.system, one of the popen methods or one of the commands.* methods? Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Alternative to standard C "for"
BJörn Lindqvist wrote: >> I am quite new to Python, and have a straight & simple question. >> In C, there is for (init; cond; advance). We all know that. >> In Python there are two ways to loop over i=A..B (numerical.): >> 1) i = A >>while i> ...do something... >> i+=STEP > > This is indeed quite ugly. You rarely need such loops in Python and > with some thinking you can often translate the C-equivalent to > something more pythonic. As you guessed, your second problem is best > solved with a generator function - xrange(). It is completely equal to > range() except that it returns a generator instead of a list. Slight terminology glitch -- it does return an iterator, not a generator. Generators are functions that return iterators. regards, Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Alternative to standard C "for"
Alex Martelli wrote: > Georg Brandl <[EMAIL PROTECTED]> wrote: > >> Slight terminology glitch -- it does return an iterator, not a >> generator. Generators are functions that return iterators. > > xrange returns an ITERABLE, not an ITERATOR. Videat: > >>>> a = xrange(23, 43) >>>> a.next() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'xrange' object has no attribute 'next' >>>> > > No next method -> not an iterator. iter(xrange(...)) DOES return an > iterator, btw. Thanks! Somehow it's always these little corrections that contain errors. And, considering your other posts today, I got away quite well... Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparison of functions
* Reinhold Birkenfeld <[EMAIL PROTECTED]> wrote: > Steven D'Aprano wrote: > 1+0j == 1 > 0 >> True > > (1+0j == 1) yields True, which is comparable to 0. "a == b > c" is equivalent to "a == b and b > c": >>> 1 == 1+0j > 0 Traceback (most recent call last): File "", line 1, in ? TypeError: cannot compare complex numbers using <, <=, >, >= -- http://mail.python.org/mailman/listinfo/python-list
Features for a Python package manager?
Hello c.l.py, what features would you expect of a Python package manager, similar to CPAN or rubygems? I am currently planning to write such a thing, at first privately for myself, and if it's proving useful, I think about releasing it. I plan to model it after gentoo's portage, with less features of course. Would this be acceptable? feel-free-to-comment-ly yours, Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Features for a Python package manager?
Robert Kern wrote: > Mike Meyer wrote: >> Nick Coghlan <[EMAIL PROTECTED]> writes: >> >> >>>I don't know enough about Portage to answer that question. I do know >>>any package manager which made it into the standard distribution would >>>need to work for at least the big three platforms (Windows/Mac/*nix) :) >> >> >> Being written in python - and hopefully integrated into Distutils - >> why shouldn't it work on any platform that Python worked on? > > Assumptions about directory structures, and the like. That is already taken care by the distutils. The various PEPs already describe a simple method how to store package metadata, and I will try to follow these standards as close as possible. Of course, the PyPI would have to be adapted for that. > IIRC, Portage was > written for the Gentoo project, so it could assume that it was > installing stuff to a Gentoo system. Package management systems have a > distressing habit of infecting their *architecture* with these > assumptions. It makes adapting them difficult. > Also, Portage needs to execute subprocesses, something which is > notoriously platform dependent. 2.4's subprocess module should probably > be used here, but I don't think Portage does, yet. OTOH, it's Gentoo, so > it wouldn't surprise me, either. :-) That's right, but I would just draw the line at Python's standard library. What is possible with it, is done, what not, is left out. regards, Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Features for a Python package manager?
Robert Kern wrote: > Georg Brandl wrote: >> Robert Kern wrote: >> >>>Mike Meyer wrote: >>> >>>>Nick Coghlan <[EMAIL PROTECTED]> writes: >>>> >>>> >>>> >>>>>I don't know enough about Portage to answer that question. I do know >>>>>any package manager which made it into the standard distribution would >>>>>need to work for at least the big three platforms (Windows/Mac/*nix) :) >>>> >>>> >>>>Being written in python - and hopefully integrated into Distutils - >>>>why shouldn't it work on any platform that Python worked on? >>> >>>Assumptions about directory structures, and the like. >> >> >> That is already taken care by the distutils. > > More or less. I'm in the middle of packaging up ~40 Python packages for > the Mac[1]. For a "standard" packaging mechanism, distutils allows for > some bloody idiosyncratic ways to say "put these files there". This is a > hard problem, and it's not solved entirely by distutils. > > I don't think anyone has satisfactorily solved the problem of > distributing data with libraries. Well, okay, the *distribution* isn't > the problem. Having the library be able to locate that data on all > platforms is difficult. Some packages will more-or-less hardcode > *nix-type paths which may be inappropriate even on some *nix-type > platforms (yes, PyX, I'm looking at you :-)). A general package system > like Portage has the freedom of being able to dictate these things. A > Python package manager does not. You can establish a standard for each > of the Big Three platforms, but it may not do you much good if the > libraries don't know about it. > > CPAN is a closer analogue in this regard and would probably be a better > tool to study and copy from than Portage. I don't know much about it, > but how it responds to these issues will probably more instructive than > how Portage does. CPAN, as I understand it, is a mirror system for packages, which downloads packages and manages those. Correct me if I'm wrong, but the actual installation is done by each package's Makefile.PL script and not by CPAN itself. This is also Portage's philosopy. It only issues those commands needed to build and install the package (ideally "tar xzf package; cd package; make install"). Of course one can do additional steps such as applying patches, but where the files go etc. is the author's responsibility, not the package system's. [Problems with dependencies] I am aware of these problems - however I feel like the package author has to be the one to address them. There must be a cooperation between author and packager to clear these issues. About non-Python-dependencies: The plan is to add a "Non-Py-Requires:" (or so) field to the metadata that is displayed to the user, and it will be his responsibility to install these libraries/headers/files first. >> The various PEPs already >> describe a simple method how to store package metadata, and I will try >> to follow these standards as close as possible. Of course, the PyPI >> would have to be adapted for that. > > Fair enough. What parts of Portage do you intend to steal, then? Right, that's my weak point. I do not overly like the PEPs' way, but integrating with distutils is the way to go. regards, Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: More elegant way to cwd?
M.E.Farmer wrote: > Peter Hansen wrote: > [snip] >> Other than using os.pardir instead of '..', and possibly adding >> an "os.path.abspath()" call to the last bit (or does realpath >> already do that? It's unclear from the docs) > [snip] > I believe os.path.abspath and os.path.realpath are the same. > realpath is just an alias for abspath. Yes, on Windows. On UNIX systems, realpath resolves symbolic links while abspath doesn't. mfg Georg -- http://mail.python.org/mailman/listinfo/python-list
"specialdict" module
Hello, in follow-up to the recent "dictionary accumulator" thread, I wrote a little module with several subclassed dicts. Comments (e.g. makes it sense to use super), corrections, etc.? Is this PEP material? Docstrings, Documentation and test cases are to be provided later. mfg Georg -- class defaultdict(dict): # _defaulttype: 0=no default, 1=defaultvalue, 2=defaultfactory __slots__ = ['_defaulttype', '_default'] def __init__(self, *args, **kwargs): self._defaulttype = 0 super(defaultdict, self).__init__(self, *args, **kwargs) def setdefaultvalue(self, value): self._defaulttype = 1 self._default = value def setdefaultfactory(self, factory, *args, **kwargs): if not callable(factory): raise TypeError, 'default factory must be a callable' self._defaulttype = 2 self._default = (factory, args, kwargs) def cleardefault(self): self._defaulttype = 0 def __getitem__(self, key): try: return super(defaultdict, self).__getitem__(key) except KeyError: if self._defaulttype == 0: raise elif self._defaulttype == 1: return self.setdefault(key, self._default) else: return self.setdefault(key, self._default[0](*self._default[1], **self._default[2])) class keytransformdict(dict): __slots__ = ['_transformer'] def __init__(self, *args, **kwargs): self._transformer = lambda x: x super(keytransformdict, self).__init__(self, *args, **kwargs) def settransformer(self, transformer): if not callable(transformer): raise TypeError, 'transformer must be a callable' self._transformer = transformer def __setitem__(self, key, value): super(keytransformdict, self).__setitem__(self, self._transformer(key), value) def __getitem__(self, key): return super(keytransformdict, self).__getitem__(self, self._transformer(key)) def __delitem__(self, key): super(keytransformdict, self).__delitem__(self, self._transformer(key)) class sorteddict(dict): def __iter__(self): for key in sorted(super(sorteddict, self).__iter__(self)): yield key def keys(self): return list(self.iterkeys()) def items(self): return list(self.iteritems()) def values(self): return list(self.itervalues()) def iterkeys(self): return iter(self) def iteritems(self): return ((key, self[key]) for key in self) def itervalues(self): return (self[key] for key in self) if __name__ == '__main__': x = sorteddict(a=1, b=3, c=2) print x.keys() print x.values() print x.items() -- http://mail.python.org/mailman/listinfo/python-list
Re: "specialdict" module
Jeff Epler wrote: > The software you used to post this message wrapped some of the lines of > code. For example: >> def __delitem__(self, key): >> super(keytransformdict, self).__delitem__(self, >> self._transformer(key)) Somehow I feared that this would happen. > In defaultdict, I wonder whether everything should be viewed as a > factory: > def setdefaultvalue(self, value): > def factory(): return value > self.setdefaultfactory(factory) That's a reasonable approach. __init__ must be changed too, but this shouldn't hurt too badly. > and the "no-default" mode would either cease to exist, or > def cleardefault(self): > def factory(): > raise KeyError, "key does not exist and no default defined" > self.setdefaultfactory(factory) > (too bad that the key isn't available in the factory, this degrades the > quality of the error messge) That can be worked around with a solution in __getitem__, see below. > if so, __getitem__ becomes simpler: > __slots__ = ['_default'] > def __getitem__(self, key): > try: > return super(defaultdict, self).__getitem__(key) > except KeyError: > return self.setdefault(key, apply(*self._default)) You are peculating the kwargs. Also, apply() is on the verge of being deprecated, so better not use it. def __getitem__(self, key): try: return super(defaultdict, self).__getitem__(key) except KeyError, err: try: return self.setdefault(key, self._default[0](*self._default[1], **self._default[2])) except KeyError: raise err Although I'm not sure whether KeyError would be the right one to raise (perhaps a custom error?). > I don't ever have an itch for sorted dictionaries, as far as I can > remember, and I don't immediately understand the use of > keytransformdict. Can you give an example of it? See the thread "Case-insensitive dict, non-destructive, fast, anyone?", starting at 04/01/05 12:38. mfg Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: "specialdict" module
Michael Spencer wrote: > 1. Given that these are specializations, why not have: > > class defaultvaluedict(dict): > ... > > class defaultfactorydict(dict): > ... > > rather than having to jump through hoops to make one implementation satisfy > both > cases I think I like Jeff's approach more (defaultvalues are just special cases of default factories); there aren't many "hoops" required. Apart from that, the names just get longer ;) > 2. I would really prefer to have the default value specified in the > constructor > > I realize that this is tricky due to the kw arguments of dict.__init__, but I > would favor either breaking compatibility with that interface, or adopting > some > workaround to make something like d= defaultvaluedict(__default__ = 0) > possible. Too much specialcased for my liking. > One worksaround would be to store the default in the dict, not as an > attribute > of the dict. By default the default value would be associated with the key > "__default__", but that keyname could be changed for the (I guess very few) > cases where that key conflicted with non-default content of the dict. Then > dict.__init__ would simply take __default__ = value as a keyword argument, as > it > does today, and __getitem__ for a missing key would return > dict.__getitem__(self, "__default__") I thought about this too (providing a singleton instance named Default, just like None is, and using it as a key), but you would have to special-case the (iter)keys,values,items methods to exclude the default - definitely too much work, and too much magic. > Alternatively, you could provide factory functions to construct the > defaultdict. > Someone (Michele?) recently posted an implementation of this Yes, I think this could be reasonable. > 3. Can you work in the tally and listappend methods that started this whole > thread off? They aren't necessary any longer. Use defaultdict.setdefaultvalue(0) instead of the tally approach and defaultdict.setdefaultfactory(list) instead of listappend. > 4. On super, no I don't think it's necessary or particularly desirable. > These > specializations have a close association with dict. dict.method(self,...) > feels > more appropriate in this case. Any other opinions on this? Thanks for the comments, mfg Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: "specialdict" module
Michael Spencer wrote: > Georg Brandl wrote: > >> >> I think I like Jeff's approach more (defaultvalues are just special >> cases of default factories); there aren't many "hoops" required. >> Apart from that, the names just get longer ;) > > Yes Jeff's approach does simplify the implementation and more-or-less > eliminates > my complexity objection > > But why do you write: > > def __getitem__(self, key): > try: > return super(defaultdict, self).__getitem__(key) > except KeyError, err: > try: > return self.setdefault(key, >self._default[0](*self._default[1], > **self._default[2])) > except KeyError: > raise err > > rather than: > > def __getitem__(self, key): > return self.setdefault(key, >self._default[0](*self._default[1], > **self._default[2])) > > (which could catch AttributeError in the case of _default not set) > I'm sure there's a reason, but I can't see it. In your version, the default factory is called every time a value is retrieved, which might be a performance problem. >>>Alternatively, you could provide factory functions to construct the >>>defaultdict. >>> Someone (Michele?) recently posted an implementation of this >> >> >> Yes, I think this could be reasonable. > > > ...though this would more naturally complement a fixed-default dictionary IMO > Your design permits - even encourages (by providing convenient setters) the > default to change over the lifetime of the dictionary. I'm not sure whether > that's good or bad, but it's a feature worth discussing. It's certainly more in the spirit of Python -- we're consenting adults, and so we are allowed to change the default. mfg Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: "specialdict" module
Michele Simionato wrote:
> About not using super: you might have problems in multiple inheritance.
> Suppose I want to use both your defaultdict and a thirdpartdict. A
> subclass
>
> class mydict(defaultdict, thirdpartdict):
>pass
>
> would not work if thirdpartdict requires a non-trivial __init__ , since
> without super in defaultdict.__init__ you would just call dict.__init__
> and not thirdpartdict.
Right. I thought about a combined defaultdict/keytransformdict,
which seems to be easy to create with the current implementation:
class defaultkeytransformdict(defaultdict, keytransformdict):
pass
At least I hope so. This is another argument against the initializing
of defaultfactory or keytransformer in __init__.
mfg
Georg
Here comes the current module (keytransformdict should be working now
for all dict methods):
# specialdict - subclasses of dict for common tasks
#
class NoDefaultGiven(Exception):
pass
class defaultdict(dict):
__slots__ = ['_default']
def __init__(self, *args, **kwargs):
self._defaulttype = 0
super(defaultdict, self).__init__(*args, **kwargs)
def setdefaultvalue(self, value):
def defaultfactory():
return value
self._default = (defaultfactory, (), {})
def setdefaultfactory(self, factory, *args, **kwargs):
if not callable(factory):
raise TypeError, 'default factory must be a callable'
self._default = (factory, args, kwargs)
def cleardefault(self):
def defaultfactory():
raise NoDefaultGiven
self._default = (defaultfactory, (), {})
def __getitem__(self, key):
try:
return super(defaultdict, self).__getitem__(key)
except KeyError, err:
try:
return self.setdefault(key, self._default[0](*self._default[1],
**self._default[2]))
except NoDefaultGiven:
raise err
class keytransformdict(dict):
__slots__ = ['_transformer']
def __init__(self, *args, **kwargs):
self._transformer = lambda x: x
super(keytransformdict, self).__init__(*args, **kwargs)
def settransformer(self, transformer):
if not callable(transformer):
raise TypeError, 'transformer must be a callable'
self._transformer = transformer
def __setitem__(self, key, value):
print "setitem"
super(keytransformdict, self).__setitem__(self._transformer(key), value)
def __getitem__(self, key):
print "getitem"
return super(keytransformdict, self).__getitem__(self._transformer(key))
def __delitem__(self, key):
super(keytransformdict, self).__delitem__(self._transformer(key))
def has_key(self, key):
return super(keytransformdict, self).has_key(self._transformer(key))
def __contains__(self, key):
return self.has_key(key)
def get(self, key, default):
return super(keytransformdict, self).get(self._transformer(key),
default)
def setdefault(self, key, default):
return super(keytransformdict, self).setdefault(self._transformer(key),
default)
def pop(self, key, default):
return super(keytransformdict, self).pop(self._transfomer(key), default)
def update(self, other=None, **kwargs):
if other is not None:
if hasattr(other, "keys"):
super(keytransformdict, self).update((self._transformer(k),
other[k]) for k in other.keys())
else:
super(keytransformdict, self).update((self._transformer(k), v)
for (k, v) in other)
if kwargs:
super(keytransformdict, self).update((self._transformer(k), v) for
(k, v) in kwargs.iteritems())
class sorteddict(dict):
def __iter__(self):
for key in sorted(super(sorteddict, self).__iter__()):
yield key
def keys(self):
return list(self.iterkeys())
def items(self):
return list(self.iteritems())
def values(self):
return list(self.itervalues())
def iterkeys(self):
return iter(self)
def iteritems(self):
return ((key, self[key]) for key in self)
def itervalues(self):
return (self[key] for key in self)
--
http://mail.python.org/mailman/listinfo/python-list
Re: "specialdict" module
Georg Brandl wrote: > Michele Simionato wrote: >> About not using super: you might have problems in multiple inheritance. >> Suppose I want to use both your defaultdict and a thirdpartdict. A >> subclass >> >> class mydict(defaultdict, thirdpartdict): >>pass >> >> would not work if thirdpartdict requires a non-trivial __init__ , since >> without super in defaultdict.__init__ you would just call dict.__init__ >> and not thirdpartdict. > > Right. I thought about a combined defaultdict/keytransformdict, > which seems to be easy to create with the current implementation: > > class defaultkeytransformdict(defaultdict, keytransformdict): > pass > > At least I hope so. This is another argument against the initializing > of defaultfactory or keytransformer in __init__. > > mfg > Georg > > Here comes the current module (keytransformdict should be working now > for all dict methods): > > # specialdict - subclasses of dict for common tasks > # > > class NoDefaultGiven(Exception): > pass > > class defaultdict(dict): > __slots__ = ['_default'] > > def __init__(self, *args, **kwargs): > self._defaulttype = 0 ^ This must read "self.cleardefault()", of course. mfg Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: re module non-greedy matches broken
lothar wrote: > give an re to find every innermost "table" element: > > innertabdoc = """ > > > >n > > > > > > > > > >y z > > > > > > > > > > > > > """ REs are Regular Expressions, not parsers. There are problems for which there is no RE solution (I'm not implying that this is the case in your example). In any case, complex text processing should be done using tools better suited to this. In this case, HTMLParser seems like a reasonable choice. mfg Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path query functions behavior incorrect?
[EMAIL PROTECTED] wrote:
> It works fine under linux
> [EMAIL PROTECTED]:~ $ python
> Python 2.3.4 (#2, Feb 2 2005, 11:10:56)
> [GCC 3.3.4 (Debian 1:3.3.4-9ubuntu5)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import os.path
>>>> os.path.exists('/blah')
> False
>>>> os.path.isdir('/blah')
> False
>>>> os.path.isdir('/home/martin')
> True
>>>> os.path.exists('/home/martin')
> True
>>>>
Of course it does. This is not a problem with Unix-style filesystems
because there a directory either exists or not. However, under Windows,
the drive letters for floppies or CDs exists even if there is no media
inserted. It is, of course, questionable whether isdir() and exists()
should return True in this case.
mfg
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: Best editor?
[EMAIL PROTECTED] wrote: > ChinStrap wrote: >> When not using the interactive prompt, what are you using? I keep >> hearing everyone say Emacs, but I can't understand it at all. I keep >> trying to learn and understand why so many seem to like it because I >> can't understand customization even without going through a hundred >> menus that might contain the thing I am looking for (or I could go >> learn another language just to customize!). > > Epsilon http://www.lugaru.com/ is a commercial Emacs-like editor with a > built-in Python mode and will automatically treat .py files as being > Python. No fiddling is required. It works well, and I spend many of my > waking hours in front of an Epsilon (even created a Fortran mode :)). I > think Epsilon is used more on Windows than Linux/Unix, where Emacs and > XEmacs have existed for a long time, but an Epsilon license contains > binaries for Linux and other Unices as well. $250 just for an Emacs clone? Sorry, but this is a bit greedy. Sure, it does some things differently, but in the same time you learn Epsilon, you can learn Emacs. > XEmacs/Emacs frustrate me, for example constantly asking if I want to > enable a "recursive mini-buffer", which I have no clue about or > interest in. Epsilon is a well-done Emacs IMO. constantly? You seem to make fundamental mistakes using Emacs. Reading one or two tutorials could have helped. mfg Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: "specialdict" module
Georg Brandl wrote: > Hello, > > in follow-up to the recent "dictionary accumulator" thread, I wrote a > little module with several subclassed dicts. > > Comments (e.g. makes it sense to use super), corrections, etc.? Is this > PEP material? > > Docstrings, Documentation and test cases are to be provided later. So, no further interest in this? Or should I write a PEP before? mfg Georg -- http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.3 release candidate 2
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I'm quite happy to announce the Python 3.3.3 release candidate 2. Python 3.3.3 includes several security fixes and over 150 bug fixes compared to the Python 3.3.2 release. This release fully supports OS X 10.9 Mavericks. In particular, this release fixes an issue that could cause previous versions of Python to crash when typing in interactive mode on OS X 10.9. Python 3.3 includes a range of improvements of the 3.x series, as well as easier porting between 2.x and 3.x. In total, almost 500 API items are new or improved in Python 3.3. For a more extensive list of changes in the 3.3 series, see http://docs.python.org/3.3/whatsnew/3.3.html To download Python 3.3.3 rc2 visit: http://www.python.org/download/releases/3.3.3/ This is a preview release, please report any bugs to http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.3's contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.22 (GNU/Linux) iEYEARECAAYFAlKB1G4ACgkQN9GcIYhpnLAu5gCfRkfpnEs+rmtZ9iTjaaZcHDx3 sNYAn180Q4cFZmKtwJdaG+g/3jHAVd97 =n/Tt -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
Re: Self-defence
Am 17.11.2013 18:33, schrieb Mark Lawrence: >> This is a last-ditch request, and not one I particularly expect to >> succeed, but I honestly can't stand to watch this happen to python-list >> for very much longer, and am very close to unsubscribing after six years >> as an admittedly not very active member. >> >> -[]z. >> > > I entirely agree with the sentiments expressed above. Would the Python > Software Foundation (I assume?) please take whatever steps it can to > prevent Nikos posting here? This is justified on the grounds of today's > behaviour alone. Add in previous days when perhaps 95% of the bandwidth > has been taken up by his posts and I know it's time to say enough is enough. As another lurking member, I can only say this: Folks, it's your decision to let this matter die. As long as python-list is coupled to Usenet, there will be little to no barrier to posting, and the only way to get rid of trolls is to ignore them. Let the barrage of posts continue for a few more days; if he doesn't get replies he will get fed up eventually. cheers, Georg -- https://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.3 final
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I'm very happy to announce the release of Python 3.3.3. Python 3.3.3 includes several security fixes and over 150 bug fixes compared to the Python 3.3.2 release. Importantly, a security bug in CGIHTTPServer was fixed [1]. Thank you to those who tested the 3.3.3 release candidate! This release fully supports OS X 10.9 Mavericks. In particular, this release fixes an issue that could cause previous versions of Python to crash when typing in interactive mode on OS X 10.9. Python 3.3 includes a range of improvements of the 3.x series, as well as easier porting between 2.x and 3.x. In total, almost 500 API items are new or improved in Python 3.3. For a more extensive list of changes in the 3.3 series, see http://docs.python.org/3.3/whatsnew/3.3.html To download Python 3.3.3 rc2 visit: http://www.python.org/download/releases/3.3.3/ This is a production release, please report any bugs to http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.3's contributors) [1] http://bugs.python.org/issue19435 -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.22 (GNU/Linux) iEYEARECAAYFAlKLDGYACgkQN9GcIYhpnLCjewCfQ+EJHpzGzIyTvYOrYmsRmnbv n40AniVM0UuQWpPrlCu349fu7Edt+d4+ =WSIj -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.4 release candidate 1
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I'm reasonably happy to announce the Python 3.3.4 release candidate 1. Python 3.3.4 includes several security fixes and over 120 bug fixes compared to the Python 3.3.3 release. This release fully supports OS X 10.9 Mavericks. In particular, this release fixes an issue that could cause previous versions of Python to crash when typing in interactive mode on OS X 10.9. Python 3.3 includes a range of improvements of the 3.x series, as well as easier porting between 2.x and 3.x. In total, almost 500 API items are new or improved in Python 3.3. For a more extensive list of changes in the 3.3 series, see http://docs.python.org/3.3/whatsnew/3.3.html and for the detailed changelog of 3.3.4, see http://docs.python.org/3.3/whatsnew/changelog.html To download Python 3.3.4 rc1 visit: http://www.python.org/download/releases/3.3.4/ This is a preview release, please report any bugs to http://bugs.python.org/ The final version is scheduled to be released in two weeks' time, on or about the 10th of February. Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.3's contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.22 (GNU/Linux) iEYEARECAAYFAlLmDI4ACgkQN9GcIYhpnLAr6wCePRbHF80k5goV4RUDBA5FfkwF rLUAnRg0RpL/b6apv+Dt2/sgnUd3hTPA =Z4Ss -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.4
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I'm very happy to announce the release of Python 3.3.4. Python 3.3.4 includes several security fixes and over 120 bug fixes compared to the Python 3.3.3 release. This release fully supports OS X 10.9 Mavericks. In particular, this release fixes an issue that could cause previous versions of Python to crash when typing in interactive mode on OS X 10.9. Python 3.3 includes a range of improvements of the 3.x series, as well as easier porting between 2.x and 3.x. In total, almost 500 API items are new or improved in Python 3.3. For a more extensive list of changes in the 3.3 series, see http://docs.python.org/3.3/whatsnew/3.3.html To download Python 3.3.4 visit: http://www.python.org/download/releases/3.3.4/ This is a production release, please report any bugs to http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.3's contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.22 (GNU/Linux) iEYEARECAAYFAlL5PMwACgkQN9GcIYhpnLCv4wCePNVqwsOYCHdJBix2bKk4PNpK GBoAnRML2x6obCssnUJe5xwuUZYw8ZSY =+/Nz -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
pathlib type error
Hi
I'm using Debian 8 Jessie on an AMD64 machine.
Getting this error:
~$ python3
Python 3.4.2 (default, Oct 8 2014, 10:45:20)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pathlib import Path
>>> p = Path("/etc")
>>> q = p / "init.d"
Traceback (most recent call last):
File "", line 1, in
TypeError: unsupported operand type(s) for /: 'PosixPath' and 'str'
>>>
This also happens if I compile python3.4.2 from scratch:
.../data/Python-3.4.2$ ./python
Python 3.4.2 (default, Jan 3 2015, 12:42:09)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pathlib import Path
>>> p = Path("/etc")
>>> q = p / "init.d"
Traceback (most recent call last):
File "", line 1, in
TypeError: unsupported operand type(s) for /: 'PosixPath' and 'str'
>>>
On the same computer, using rescuecd 4.4.1 (Nov 2014) which ships python
3.4.1 it works as expected.
thanks for help, Georg
--
https://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.5 release candidate 1
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I'm happy to announce the release of Python 3.3.5, release candidate 1. Python 3.3.5 includes a fix for a regression in zipimport in 3.3.4 (see http://bugs.python.org/issue20621) and a few other bugs. Python 3.3 includes a range of improvements of the 3.x series, as well as easier porting between 2.x and 3.x. In total, almost 500 API items are new or improved in Python 3.3. For a more extensive list of changes in the 3.3 series, see http://docs.python.org/3.3/whatsnew/3.3.html To download Python 3.3.5 visit: http://www.python.org/download/releases/3.3.5/ This is a preview release, please report any bugs to http://bugs.python.org/ The final release is scheduled one week from now. Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.3's contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.22 (GNU/Linux) iEYEARECAAYFAlMKIPEACgkQN9GcIYhpnLCjXACfQwbC/eD/lhKAZ+XCwTwYPVWj GMwAnjWkbdk7hqsKoh12EiagpGApEPSA =2BCx -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.5 release candidate 2
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I'm happy to announce the release of Python 3.3.5, release candidate 2. Python 3.3.5 includes a fix for a regression in zipimport in 3.3.4 (see http://bugs.python.org/issue20621) and a few other bugs. Python 3.3 includes a range of improvements of the 3.x series, as well as easier porting between 2.x and 3.x. In total, almost 500 API items are new or improved in Python 3.3. For a more extensive list of changes in the 3.3 series, see http://docs.python.org/3.3/whatsnew/3.3.html To download Python 3.3.5 visit: http://www.python.org/download/releases/3.3.5/ This is a preview release, please report any bugs to http://bugs.python.org/ The final release is scheduled one week from now. Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.3's contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.22 (GNU/Linux) iEYEARECAAYFAlMUUKoACgkQN9GcIYhpnLD5OACfTpRkcM9aXUx2XbiXoZtIgSE7 BqwAnjwpAuqc9lKJ0O3XOw5qDvDPYsNb =EGuB -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.5
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I'm very happy to announce the release of Python 3.3.5. Python 3.3.5 includes fixes for these important issues: * a 3.3.4 regression in zipimport (see http://bugs.python.org/issue20621) * a 3.3.4 regression executing scripts with a coding declared and Windows newlines (see http://bugs.python.org/issue20731) * potential DOS using compression codecs in bytes.decode() (see http://bugs.python.org/issue19619 and http://bugs.python.org/issue20404) and also fixes quite a few other bugs. Python 3.3 includes a range of improvements of the 3.x series, as well as easier porting between 2.x and 3.x. In total, almost 500 API items are new or improved in Python 3.3. For a more extensive list of changes in the 3.3 series, see http://docs.python.org/3.3/whatsnew/3.3.html To download Python 3.3.5 visit: http://www.python.org/downloads/release/python-335/ This is a production release, please report any bugs to http://bugs.python.org/ The final release is scheduled one week from now. Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.3's contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.22 (GNU/Linux) iEYEARECAAYFAlMcRNEACgkQN9GcIYhpnLAVqACeMoOOuuNX5iP6at9zbIZDnkqK idwAoKb2FxAJlirhs2BmdESEaQiqBDJd =smeC -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.3.3 release candidate 1
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I'm quite happy to announce the Python 3.3.3 release candidate 1. Python 3.3.3 includes several security fixes and over 150 bug fixes compared to the Python 3.3.2 release. This release fully supports OS X 10.9 Mavericks. In particular, this release fixes an issue that could cause previous versions of Python to crash when typing in interactive mode on OS X 10.9. Python 3.3.3 also contains a new batteries-included feature for OS X users of IDLE and other Tkinter-based programs. The python.org Mac OS X 64-bit/32-bit x86-64/i386 Installer for OS X 10.6+ now includes its own builtin version of Tcl/Tk 8.5. It is no longer necessary to install a third-party version of Tcl/Tk 8.5 to workaround the problematic system versions. See http://www.python.org/download/mac/tcltk/ for more information. Python 3.3 includes a range of improvements of the 3.x series, as well as easier porting between 2.x and 3.x. In total, almost 500 API items are new or improved in Python 3.3. For a more extensive list of changes in the 3.3 series, see http://docs.python.org/3.3/whatsnew/3.3.html and for the detailed changelog of 3.3.3, see http://docs.python.org/3.3/whatsnew/changelog.html To download Python 3.3.3 rc1 visit: http://www.python.org/download/releases/3.3.3/ This is a preview release, please report any bugs to http://bugs.python.org/ The final version is scheduled to be released in two weeks' time, on or about the 10th of November. Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.3's contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.22 (GNU/Linux) iEYEARECAAYFAlJte8kACgkQN9GcIYhpnLDx8wCgqtabbC8DaoW+Vy03AYGWyLhw sWcAoIK5jQeXDAxHayG+VWH/rRF1+qHC =yOed -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
Re: Problem installing matplotlib 1.3.1 with Python 2.7.6 and 3.3.3 (release candidate 1)
Am 04.11.2013 01:59, schrieb Ned Deily: > In article <[email protected]>, > Piet van Oostrum wrote: >> I tried to install matplotlib 1.3.1 on the release candidates of Python >> 2.7.6 >> and 3.3.3. > > [...] > > Please open an issue on the Python bug tracker for the Python component of > this. > > http://bugs.python.org And please mark as release blocker, I think this should go into 3.3.3rc2. Georg -- https://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.2.6rc1, Python 3.3.6rc1
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I'm happy to announce the release of Python 3.2.6rc1 and 3.3.6rc1. Both are release candidates for security-fix releases, which are provide source-only on python.org. The list of security-related issues fixed in the releases is given in the changelogs: https://hg.python.org/cpython/raw-file/v3.2.6rc1/Misc/NEWS https://hg.python.org/cpython/raw-file/v3.3.6rc1/Misc/NEWS To download the pre-releases visit one of: https://www.python.org/downloads/release/python-326rc1/ https://www.python.org/downloads/release/python-336rc1/ These are pre-releases, please report any bugs to http://bugs.python.org/ The final releases are scheduled one week from now. Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2 iEYEARECAAYFAlQv9GsACgkQN9GcIYhpnLC93gCfVm74lhOysPYCO0fy9/l5LUfJ bUYAn2u1EygfsPw2oa4CSoj5t0TYUJq7 =HnOK -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.2.6, Python 3.3.6
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I'm happy to announce the release of Python 3.2.6 and 3.3.6. Both are security-fix releases, which are provided source-only on python.org. The list of security-related issues fixed in the releases is given in the changelogs: https://hg.python.org/cpython/raw-file/v3.2.6/Misc/NEWS https://hg.python.org/cpython/raw-file/v3.3.6/Misc/NEWS To download the releases visit one of: https://www.python.org/downloads/release/python-326/ https://www.python.org/downloads/release/python-336/ These are production versions, please report any bugs to http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2 iEYEARECAAYFAlQ6L/cACgkQN9GcIYhpnLBxIwCeLqjXeIOxGA2vkjbkN5Ic6j2u 7WcAoKgFaB4drMX5ZOVUJ4VLyNTcfycN =KLlw -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.2.4 rc 1 and Python 3.3.1 rc 1
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I am pleased to announce the first release candidates of Python 3.2.4 and 3.3.1. Python 3.2.4 will be the last regular maintenance release for the Python 3.2 series, while Python 3.3.1 is the first maintenance release for the 3.3 series. Both releases include hundreds of bugfixes. There has recently been a lot of discussion about XML-based denial of service attacks. Specifically, certain XML files can cause XML parsers, including ones in the Python stdlib, to consume gigabytes of RAM and swamp the CPU. These releases do not include any changes in Python XML code to address these issues. Interested parties should examine the defusedxml package on PyPI: https://pypi.python.org/pypi/defusedxml These are testing releases: Please consider trying them with your code and reporting any bugs you may notice to: http://bugs.python.org/ To download Python 3.2.4 or Python 3.3.1, visit: http://www.python.org/download/releases/3.2.4/ or http://www.python.org/download/releases/3.3.1/ respectively. Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and all contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.19 (GNU/Linux) iEYEARECAAYFAlFRRIoACgkQN9GcIYhpnLD6jACgnzYdYRKZ4kwkKeN3zSLSZ3Zr M/IAn17vlpxI3a3xk+i/ODOrCkMnRZro =B5sA -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.2.4 and Python 3.3.1
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team, I am pleased to announce the final releases of Python 3.2.4 and 3.3.1. Python 3.2.4 is the final regular maintenance release for the Python 3.2 series, while Python 3.3.1 is the first maintenance release for the 3.3 series. Both releases include hundreds of bugfixes. There has recently been a lot of discussion about XML-based denial of service attacks. Specifically, certain XML files can cause XML parsers, including ones in the Python stdlib, to consume gigabytes of RAM and swamp the CPU. These releases do not include any changes in Python XML code to address these issues. Interested parties should examine the defusedxml package on PyPI: https://pypi.python.org/pypi/defusedxml To download Python 3.2.4 or Python 3.3.1, visit: http://www.python.org/download/releases/3.2.4/ or http://www.python.org/download/releases/3.3.1/ respectively. As always, please report bugs to http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and all contributors) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.19 (GNU/Linux) iEYEARECAAYFAlFgiN8ACgkQN9GcIYhpnLAXxQCdHAd2lECpYfmYM4Wbd3I01es4 898AoKBDvHtgecD/PeVRKUrdQRSWGPJg =K8RQ -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: [RELEASED] Python 3.2.4 and Python 3.3.1
Am 06.04.2013 22:48, schrieb cmcp: > On Saturday, 6 April 2013 21:43:11 UTC+1, Georg Brandl wrote: >> -BEGIN PGP SIGNED MESSAGE- >> >> Hash: SHA1 >> >> >> >> On behalf of the Python development team, I am pleased to announce the >> >> final releases of Python 3.2.4 and 3.3.1. >> > The Python 3.3.1 Release page on python.org still says "This is a preview > release, and its use is not recommended in production settings." I'm > assuming this is just an oversight? Yes. Thanks for the report, it's fixed now. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Restricted Access
Cameron Laird wrote: > In article <[EMAIL PROTECTED]>, > iapain <[EMAIL PROTECTED]> wrote: > . > . > . >>Does that mean there is no way to implement restricted enviorment? > . > . > . > The most knowledgeable people have effectively given up, in > regard to Python. Brett Cannon is currently trying to come up with a comprehensive spec and implementation of a sandboxed Python interpreter, for use in Mozilla as a JavaScript replacement. (look in the python-dev archives for more) Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Abuse of the object-nature of functions?
Carl J. Van Arsdall wrote: > Hrmms, well, here's an interesting situation. So say we wanna catch > most exceptions but we don't necessarily know what they are going to > be. For example, I have a framework that executes modules (python > functions), the framework wraps each function execution in a try/except > block in order to compensate for what *might* happen. Upon coding the > framework I really have no idea what types of problems these modules > might have but I want to catch these errors so that I can clean up and > exit gracefully, not only that but I want to dump the exception to log > files so that we can attempt to fix it. So, I have the option of > catching all standard exceptions and not list the ones I know I don't > want to catch. But what about user defined exceptions? Do I then have > to enforce policies on the system stating what types of exceptions can > be raised? > > Is there a way in python to say, "hey, catch everything but these two"? Yes: try: ...some code... except (AttributeError, TypeError): raise except Exception, e: handle all other exceptions is the most Pythonic solution. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: inheritance, types, operator overload, head ache
[EMAIL PROTECTED] wrote:
>> > > Can some one *please* splain me why str(obj) works but not print obj,
>> >
>> > May have something to do with escape chars... I tried with:
>> >def __str__(self):
>> > return repr(self)
>
> Yes, that appears to be correct. Experiments indicated that it's an
> issue with escaping.
>
>
>> > What you want here is to first create the instance, and only then bind
>> > to it:
>> >
>> > def __new__(cls, val):
>> > if type(val) == str and not val.isdigit():
>> > val = struct.unpack('B', val)
>> > _byte = struct.pack('B', val)
>> > self = str.__new__(cls, _byte)
>> > self._byte = _byte
>> > self._int = int(val)
>> > return self
>
> Oh, I see. I tried that and it worked well, but the broken int(obj) is
> too annoying.
The problem is that int() checks if the argument is a string (which includes
subclasses) and directly tries to convert the string without looking at
__int__. If you want, you can report this as a bug and see if other
developers agree.
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: Abuse of the object-nature of functions?
Ant wrote: >> Is there a way in python to say, "hey, catch everything but these two"? > >>>> try: > ... raise AttributeError > ... except Exception, ex: > ... if isinstance(ex, AttributeError): > ... print "Won't catch it!" > ... raise ex > ... > > Won't catch it! > Traceback (most recent call last): > File "", line 7, in ? > AttributeError > > Or that sort of thing. To just reraise an exception, use a bare "raise". Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Abuse of the object-nature of functions?
Ant wrote: >> > try: >> > # Do some stuff >> > except Exception, err: >> > if err not in (DontCatchMe1, DontCatchMe2): >> > # Handle err >> > >> > HTH, >> > ~Simon >> >> Dang! not only did somebody else beat me to it, but my code is wrong >> and theirs correct. > > Ignoring the fact you haven't re-raised the exception (as we can ignore > the fact mine doesn't handle the others ;-) ), it does show a different > valid approach: mine has an advantage if the exceptions you don't want > to handle inherit from a small number of base classes; yours has the > advantage if there are a large number of unrelated exceptions that need > ignoring. His code is wrong since "err" is not the exception class but an instance. "if type(err) ..." would be correct but unpythonic. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: timeit module for comparing the performance of two scripts
3c273 wrote: > "John Machin" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> You appear to know what a switch is. I'm therefore surprised that you >> appear not to >> know that the convention is that any program that uses >> command-line switches should do something informative when run with a -h >> switch. >> > Doh! Me thinks Windows at work "python /?" (No good!), Linux at home > "python -h" (Ah ha!). I still think it should be in the docs somewhere. python /? now works in 2.5 SVN. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
Lawrence D'Oliveiro wrote: > In message <[EMAIL PROTECTED]>, Bob Greschke wrote: > >> I'd go even one step further. Turn it into English (or your favorite >> non-computer language): >> >> 1. While list, pop. >> >> 2. While the length of the list is greater than 0, pop. >> >> Which one makes more sense? Guess which one I like. CPU cycles be >> damned. >> :) > > One of my rules is, always program like the language actually has a Boolean > type, even if it doesn't. That means, never assume that arbitrary values > can be interpreted as true or false, always put in an explicit comparison > if necessary so it's obvious the expression is a Boolean. You can do that, but it's not considered Pythonic. And it might be ineffective. Other than in PHP, Python has clear rules when an object of a builtin type is considered false (i.e. when it's empty). So why not take advantage of this? Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style
Antoon Pardon wrote: >> Other than in PHP, Python has clear rules when an object of a builtin type >> is considered false (i.e. when it's empty). So why not take advantage of >> this? > > Because it doesn't always do what I want. > > I once had a producer consumer code. When the client asked whether new > items were available the function could return three different values > > 1) a list with items, to be consumed > 2) an empty list (meaning there were no items available for the > moment but there could be in the future > 3) None (meaning the producer was done) > > Just testing for the truth value of the returned result in order > to see whether the client should continue or not would often > have made the client exit prematurely. > > IME such cases where testing for the truth value of an object > don't give the expected result, happen often enough to make me > carefully think about what I want to test for and then explicitly > do so. You're right, carefully thinking is always a good thing. Not using a language feature just because it would fail in another case is not. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: How to recognise "generator functions" ?
imho wrote: > Hi all. > > Is there a way to know if a function object is actually a "generator > function" or not ? e.g.: > > def f(): > pass > > def g(): > yield None > > f.__class__ is the same as g.__class__ , i.e. "function" type. > But i "know" that the second, when invoked, returns a generator object, > because there is a "yield" statement in its body. > > Is there a (eventually hackish) method to get such information ? >>> f.func_code.co_flags 67 >>> g.func_code.co_flags 99 => 32 (CO_GENERATOR in compiler.consts) is the flag that indicates a generator code object. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I optimise this? [intended in good humour]
John Machin wrote:
> Markus wrote:
>> You know you're guilty of early/over optimisation, when it's almost two
>> in the morning and the file open in front of you reads as follows.
>>
>> The code you are about to read is real...
>> Some of the variable names have been changed
>> to protect the families of those involved.
>>
>> [-snip-]
>>
>> from timeit import Timer
>>
>> if __name__=='__main__':
>> t = Timer('len(argv)==1','from sys import argv')
>> print "%f usec/pass" % (100 * t.timeit(number=10)/10)
>> t = Timer('argv[0]==argv[-1]','from sys import argv')
>> print "%f usec/pass" % (100 * t.timeit(number=10)/10)
> Do you realise that the two expressions that you are comparing are not
> even equivalent, and moreover you ignored an expression that will be
> faster and equivalent (unless/until somebody decides on an
> "optimisation" like interning/sharing strings between/among sys.argv
> elements).
Let me point out that len(argv) == 1 is the only one that will work if
argv is []. ;) (took me a few seconds to realize I must put a smiley there)
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: New release of Diet Python (0.2 Beta)!!!
The Eternal Squire wrote: > Diet Python is a flavor of Python with allegro, multiarray, umath, > calldll, npstruct and curses builtin, all else nonessential to language > > ripped out. Total size < 3MB, 1% of PSF Python. Diet Python helps keep > clients thin :) Erm... Which "PSF Python" are you referring to? I can't find a distribution that's 300 MB in size... Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: New release of Diet Python (0.2 Beta)!!!
The Eternal Squire wrote: > A developer's installation of PSF, including Pywin, WxPython, Numpy, > Scipy I believe can run up to 300 MB, no? > > Otherwise, I'll put up a different percentage. Well, if you refer to a Python installation including all these packages (anyway, I don't think it would be so large) you should not call that "PSF Python". The Python Windows installer available from python.org is around 10, the source distribution around 8 MB. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Ann: SE 2.2b
[EMAIL PROTECTED] wrote: > Frederic> In the short period of time since I introduced SE. the > Frederic> feedback has been overwhelmingly postive. > > Ummm... what is it? The last SE I had was a Mac. It is supposed to be a Stream Editor (in the spirit of sed, I think). However, the PyPI page provides no download or homepage links. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Ann: SE 2.2b
Anthra Norell wrote: > If you go to http://www.python.org/pypi. you see it about in the middle of > the recently updated packages. It's blue, so you can > click it and you're there. > The update page shows only the twenty most recent updates. So they drop > out at the bottom rather fast. If it's gone by the > time you check, type SE into the search template in the upper right corner. Thanks, but I know how to use the Cheese Shop. Last time I looked, there was no file available for download. Now it is. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: singleton decorator
Andre Meyer wrote:
> While looking for an elegant implementation of the singleton design
> pattern I came across the decorator as described in PEP318
> <http://www.python.org/dev/peps/pep-0318/>.
> Unfortunately, the following does not work, because decorators only work
> on functions or methods, but not on classes.
>
> def singleton(cls):
> instances = {}
> def getinstance():
> if cls not in instances:
> instances[cls] = cls()
>
> return instances[cls]
> return getinstance
>
> @singleton
> class MyClass:
> ...
>
>
> Am I missing something here? What is the preferred pythonic way of
> implementing singleton elegantly?
You can always use the syntax the decorator replaces:
class MyClass:
...
MyClass = singleton(MyClass)
But there are better ways, and maybe you don't even need a singleton.
See the Python Cookbook.
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: do people really complain about significant whitespace?
Gerhard Fiedler wrote: > function() > loop1() > blah > blah > > loop2() > blah > > loop3() > blah > #end loop3() > > blah3 > #end loop2() > #end loop1() > > otherloop() > blah > #end otherloop() > #end function() > > Of course, few people will write like this, but it probably is easier to > write a Python code formatter that adds them than it is to write a C code > formatter that adds proper indentation and provides your preferred > placement of braces. It's already there: Tools/scripts/pindent.py. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Optimization of __len__() in cgi.py
Bob Kline wrote:
> I have a suggestion for speeding up the performance of code like this:
>
> fields = cgi.FieldStorage()
> if fields: ...
>
> which, as it turns out, invokes FieldStorage.__len__(), which in turn
> calls FieldStorage.keys(), which builds a list of keys by hand, taking
> several minutes for large forms. This implementation of keys() reduces
> the amount of time taken by several orders of magnitude:
>
> def keys(self):
> return {}.fromkeys([i.name for i in self.list]).keys()
>
> Is there a better place for submitting suggestions like this?
Post a RFE to the Python Tracker at
http://sourceforge.net/tracker/?group_id=5470&atid=355470
If you want, assign it to me (gbrandl).
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: sum and strings
Paul Rubin wrote: > Sybren Stuvel <[EMAIL PROTECTED]> writes: >> Because of "there should only be one way to do it, and that way should >> be obvious". There are already the str.join and unicode.join methods, > > Those are obvious??? Why would you try to sum up strings? Besides, the ''.join idiom is quite common in Python. In this special case, ''.join is much faster than sum() which is why sum() denies to concat strings. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Clean way to not get object back from instantiation attempt gone bad
tobiah wrote:
> Suppose I do:
>
>
> myfoo = Foo('grapes', 'oranges')
>
> And in the __init__() of Foo, there is
> a real problem with the consumption of fruit.
> Is there a clean way to ensure that myfoo
> will be None after the call? Would the
> __init__() just do del(self), or is there
> a better way to think about this?
There is a way, of course, that results in myfoo
being None in case of an error, but it is not a one-liner and
I'd not recommend it.
If something goes wrong, raising an exception is the best thing to do.
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: sum and strings
Paddy wrote: > Sybren Stuvel wrote: >> Paddy enlightened us with: >> > Well, after all the above, there is a question: >> > >> > Why not make sum work for strings too? >> >> Because of "there should only be one way to do it, and that way should >> be obvious". There are already the str.join and unicode.join methods, >> which are more powerful than sum. >> >> Sybren > I get where you are coming from, but in this case we have a function, > sum, that is not as geeral as it could be. sum is already here, and > works for some types but not for strings which seems an arbitrary > limitation that impede duck typing. Only that it isn't arbitrary. > - Pad. > > P.S. I can see why, and am used to the ''.join method. A newbie > introduced to sum for integers might naturally try and concatenate > strings using sum too. Yes, and he's immediately told what to do instead. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you get the name of a dictionary?
Andy Terrel wrote:
> Why bang your head?
Because there's no chance that the original request is sane.
If you want your objects to know their name, give them a name as an attribute.
> It was a stupid hack that has lots of problems,
> but done in a way that is readable. Sure I could do something more
> functional or one lined like:
>
> Banana={}
> names = filter(lambda x:id(eval(x))==id(Banana),dir())
>
> but I am guessing that it is harder to read by many. Anywho I can
> think of plenty of reasons it would fail, but it really depends on the
> app.
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: sum and strings
Paul Rubin wrote: > Georg Brandl <[EMAIL PROTECTED]> writes: >> Why would you try to sum up strings? Besides, the ''.join idiom is quite >> common in Python. > > Just because it's common doesn't mean it's obvious. In my opinion > it's as ugly as sin, and the fact that it's an idiom shows a > shortcoming in Python. The obvious reason for summing strings is that > it's a long-established feature of Python that a+b concatenates two > strings, so summing a,b,c,d,e should result in a+b+c+d+e. Which is exactly how I would concatenate five strings. For concatenating longer sequences of strings, however, if it needs to be done fast, performance-wise, this approach is not sensible. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: sum and strings
Bill Pursell wrote: > Georg Brandl wrote: >> Paul Rubin wrote: >> > Sybren Stuvel <[EMAIL PROTECTED]> writes: >> >> Because of "there should only be one way to do it, and that way should >> >> be obvious". There are already the str.join and unicode.join methods, >> > >> > Those are obvious??? >> >> Why would you try to sum up strings? Besides, the ''.join idiom is quite >> common in Python. > > One could extend this argument to dissallow the following: >>>> "foo" + "bar" Fortunately, hypergeneralization is not one of Python's weaknesses. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: import
[EMAIL PROTECTED] wrote: > bugnthecode 写道: > >> How are you trying to import it? Is it in the same directory as your >> other script? If not is your python path set correctly? >> >> When importing a module that you have written you exlude the .py >> extension. You should be using: >> import hello >> >> Hope that helps, >> Will > > i am on a windows platform. i have written scrip named 123.py. it can > be run. ok i save it to C:\Python24 ,exactly the same dir where python > works. but " import 123" doesnt work. You can't import modules whose names have non-identifier names with plain "import". Or would you like "123" to refer to a module? If you have to do this (and I have a strong feeling that you haven't) use the built-in function __import__(). Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: import
01 wrote: > Georg Brandl wrote: >> [EMAIL PROTECTED] wrote: >> > bugnthecode 写道: >> > >> >> How are you trying to import it? Is it in the same directory as your >> >> other script? If not is your python path set correctly? >> >> >> >> When importing a module that you have written you exlude the .py >> >> extension. You should be using: >> >> import hello >> >> >> >> Hope that helps, >> >> Will >> > >> > i am on a windows platform. i have written scrip named 123.py. it can >> > be run. ok i save it to C:\Python24 ,exactly the same dir where python >> > works. but " import 123" doesnt work. >> >> You can't import modules whose names have non-identifier names with >> plain "import". Or would you like "123" to refer to a module? >> >> If you have to do this (and I have a strong feeling that you haven't) >> use the built-in function __import__(). >> > you have to name your program with the name mymodule,or something like > that when you use "import". does python have a clear declaration on > how to name a module? A module name can be everything also usable as a Python identifier. This means that it contains only letters, digits and underscores and doesn't start with a digit. Running a file as the main file, using "python 123.py" works because Python then won't need to provide the file name as a name in the script. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Input from the same file as the script
[EMAIL PROTECTED] wrote:
> Can the input to the python script be given from the same file as the
> script itself. e.g., when we execute a python script with the command
> 'python
> When I ran the below the python interpreter gave an error.
*sigh* Why do you think that we could guess what error this may be?
In this case, it is likely a SyntaxError because you used input() instead
of raw_input().
> e.g.,
> scriptName:
> ---
> x = input("The value of x is taken from the source code file itself as
> input is redirected to it")
>
> print x
>
> "Value intended for the variable x"
>
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: sum and strings
Steven D'Aprano wrote:
> On Fri, 18 Aug 2006 19:08:37 -0700, Paul Rubin wrote:
>
>> If the args are strings, the above is a quadratic time algorithm and
>> it's better to throw an error than create such a trap for an unwary user.
>
> That's a nonsense argument. There is no shortage of slow algorithms, and
> some of them are built into Python. When did O(n**2) become an error
> condition? And overhead matters: if I'm only doing a few concatenations,
> it is significantly faster to add the strings using + than to use join()
> (at least in Python 2.3 -- YMMV):
>
>>>> s = timeit.Timer("''.join(L)", "L=['a'*50, 'b'*50, 'c'*50]")
>>>> s.timeit()
> 1.3470098972320557
>>>> t = timeit.Timer("a+b+c", "a,b,c = 'a'*50, 'b'*50, 'c'*50")
>>>> t.timeit()
> 1.0698421001434326
>
> There's a word for optimizations that actually result in code running 25%
> slower.
>
> I applaud that Python's language developers care about efficiency. I
> applaud that the documentation warns people about traps and potential
> areas of inefficiency. But I think it is a shame that sum() does a
> special type-check to avoid something which is only sometimes slow. It
> doesn't protect against O(n**2) performance; it merely protects against
> just one of an infinite number of possible "traps for the unwary".
>
> I would have thought it would be better for sum() to raise a warning, not
> an exception. If we take seriously the argument that sum implies
> addition, and that string concatenation isn't really addition, then sum()
> should also refuse to operate on lists and tuples and any other
> non-numeric class. Either would be better than sum() "protecting" the user
> from himself, except when it doesn't.
Well, present that on python-dev.
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: Problem of function calls from map()
Paul McGuire wrote:
> "Dasn" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>>
>> Hi, there.
>>
>> 'lines' is a large list of strings each of which is seperated by '\t'
>> >>> lines = ['bla\tbla\tblah', 'bh\tb\tb', ... ]
>>
>> I wanna split each string into a list. For speed, using map() instead
>> of 'for' loop.
>
> Try this. Not sure how it stacks up for speed, though. (As others have
> suggested, if 'for' loop is giving you speed heartburn, use a list
> comprehension.)
>
> In this case, splitUsing is called only once, to create the embedded
> function tmp. tmp is the function that split will call once per list item,
> using whatever characters were specified in the call to splitUsing.
>
> -- Paul
>
>
>
> data = [
> "sldjflsdfj\tlsjdlj\tlkjsdlkfj",
> "lsdjflsjd\tlsjdlfdj\tlskjdflkj",
> "lskdjfl\tlskdjflj\tlskdlfkjsd",
> ]
>
> def splitUsing(chars):
> def tmp(s):
> return s.split(chars)
> return tmp
>
> for d in map(splitUsing('\t'), data):
> print d
And why is this better than
map(lambda t: t.split('\t'), data)
?
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: CONSTRUCT - Module Attributes and Execution Environment
Larry Bates wrote: > lazaridis_com wrote: >> I would like to change the construct: >> >> if __name__ == '__main__': >> >> to something like: >> >> if exec.isMain(): >> >> My (OO thought) is to place a class in an separate code module and to >> instantiate an singleton instance which would keep th something like >> this: >> >> class ExecutionEnv: >> def isMain(self) >> if CALLING_MODULE.__name__ == '__main__': >> return true >> else >> return false >> >> exec = ExecutionEnv() >> >> How to I get access to the CALLING_MODULE ? >> >> - >> >> Are ther alternative constructs/mechanism available, which could be >> used to add this functionality possiby directly to a code-module? >> > Two thoughts: > > 1) Don't call a class instance exec, it will mask the built-in > exec statement. He won't be able to ;) Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you get the name of a dictionary?
jojoba wrote: > Hello again, > > Fredrick said: > >> Python's object model. an object has a value, a type, and an identity, >> but no name. > > I say: > > Thank you Fredrick for the reply! > However, although python's object model does not currently support what > i am asking for, how difficult would it be to assign a string name(s) > to an object upon creation (and upon referencing)? > > please note: > i don't want to do anything sophisticated with this, i am really only > looking for a TITLE for my dictionary when i throw it in a tree editor > that i have built. And i do realize that its not possible now. I am > just pressing a point here. > > Sorry to ruffle everyone's feathers, but this is a fairly curious > problem. Why not add a "name" attribute to your objects? e.g. class NamedDict(dict): def __init__(self, _name_, *args, **kwargs): self.name = _name_ dict.__init__(self, *args, **kwargs) Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you get the name of a dictionary?
Steven D'Aprano wrote:
> On Tue, 22 Aug 2006 10:12:00 -0700, BartlebyScrivener wrote:
>
>>>> how difficult would it be to assign a string name(s)
>>>> to an object upon creation (and upon referencing)?
>>
>> Exactly the point that's being made. It's so easy just do it yourself:
>>
>> banana={"name":"banana"}
>>
>> Hey what is the name of my dictionary?
>>
>> banana["name"]
>>
>> But why build it into Python and force everyone else to do it, when
>> most of the time nobody cares what the name is, or they already know?
>>
>> It's like forcing everybody everywhere always and forever to wear
>> "Hello My Name Is" tags.
>
> On reflection, I'm wondering if we've been too harsh on Jojoba and not
> thought this through, simply because "that's the way it's always been".
>
> Functions have a __name__ attribute. So do classes and modules. Why are
> these three objects "special" that they know the name they were created
> with, when other objects don't? Python doesn't attempt to track what name
> they are known at *now*, just the name they were born with.
Because they're not created by simple assignment, because they are
usually created once, because new names are bound to them rarely,
and because it's crucial to know their name in debugging, introspection etc.
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: how do you get the name of a dictionary?
jojoba wrote:
>> And what im saying is that isnt it silly that we need pass an entire
>> namespace, when a much simpler notion would be to have each object know
>> its own name(s) (even if that name doesnt exist).
>
>
> please note: in my above comment, i was completely disregarding any
> notions of added costs that would be incurred to have such a feature,
> and that in fact, such costs might actually nullify any other benefits
> from having such a feature. Purely a what-if idea from a nascent python
> programmer.
Even from such a point of view, the concept isn't clearly enough defined.
What name would be assigned to the dict below?
l = [1,2,3]
a = "some_str"
l[0] = {'foo': 'bar'}
Some immutable objects, such as small integers, exist only once. Would you
assign names to them? They're likely to be completely meaningless.
When a name goes out of scope, but the object continues to live (e.g.
because it's returned by some function), the name is void.
Etc.
Georg
--
http://mail.python.org/mailman/listinfo/python-list
Re: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 23)
Jack Diederich wrote: > QOTW: "Because there's no chance that the original request is sane." - Georg > Brandl (responding to a question involving a Banana) Looks like I'm trying to fulfil my bot duties from time to time ;) > "this is one of your last chances to test the new code in 2.5 before the final > release. *Please* try this release out and let us know about any problems you > find" - Anthony Baxter, Python Release Manager > > > sum() is for numbers. It doesn't work with strings for your protection. > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/e782a88bf5b2f911/ > > Parsing valid email addresses is hard. > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/dfb305247edd7c6c/ > > Q: How do I make my code python 3000 compatible? > A: Wait for python 3000. > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/8aee8423747c094d/ > > The C++ STL can't match python's speed in some applications. > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/94fed9a76015a5e4/ > > David Wahler is no longer out of the office. > http://groups.google.com/groups/search?q=David+Wahler+out+of+office Thanks for pointing that out, Jack ;) Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: What value should be passed to make a function use the default argument value?
Paul Rubin wrote: > Antoon Pardon <[EMAIL PROTECTED]> writes: >> repeat(object[, times]) >> Make an iterator that returns object over and over again. Runs >> indefinitely unless the times argument is specified. ... >> >> My first impression from this, is that it is possible to call >> this as follows: >> repeat(None, times = 5) >> But that doesn't work either. > > The code and/or doc is wrong, you have to use a positional arg > and not a named one. repeat(None, 5) does the right thing. This is an issue in most Python documentation: you're not told if the described function is implemented in C, and if it is keyword arg-enabled. The arguments must be given names though, to be able to document them. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Python to use a non open source bug tracker?
Ilias Lazaridis wrote: > Giovanni Bajo wrote: >> Hello, >> >> I just read this mail by Brett Cannon: >> http://mail.python.org/pipermail/python-dev/2006-October/069139.html >> where the "PSF infrastracture committee", after weeks of evaluation, >> recommends >> using a non open source tracker (called JIRA - never heard before of course) >> for Python itself. >> >> Does this smell "Bitkeeper fiasco" to anyone else than me? >> -- >> Giovanni Bajo > > Fascinating. > > The python foundation suggests a non-python non-open-source bugtracking > tool for python. Actually, it suggests two bugtracking tools, one of them written in Python. > It's like saying: "The python community is not able to produce the > tools needed to drive development of python forward." No, it's saying: "if the Python community is able to provide the required amount of time to do the admin work, we'll use the tool written in Python." > Anyway. The whole selection process is intransparent. Steve has already pointed you to the wiki page. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Python to use a non open source bug tracker?
Fredrik Lundh wrote: > Georg Brandl wrote: > >>> The python foundation suggests a non-python non-open-source bugtracking >>> tool for python. >> >> Actually, it suggests two bugtracking tools, one of them written in >> Python. > > the announcemant's subject line said "recommendation for a new issue > tracker", though; not "we need the community's help before we can make a > final recommendation". Granted. > in fact, only 20% of the announcement talked about Python; the rest was > something that looked a lot like a press release from the non-python > hosting company, so it's not that strange that people missed the few > sentences in the middle that explained that the subject line wasn't > entirely accurate. I actually stopped reading after Brett's signature, so I didn't have the 20% figure in my mind :) Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Metaprogramming question
Steve Menard wrote: > I have a need to create class instance without invokking the class' __init__ > method. > > Were I using old-style classes, I'd use new.instance() function. However, I > am using new-style classes and new.instance() complain "TypeError: > instance() argument 1 must be classobj, not type" ... > > So my question is, how to replicate new.instance() functionality with new > classes? Use object.__new__. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatic import PEP
Dan Bishop wrote: > On Sep 22, 10:09 pm, Connelly Barnes <[EMAIL PROTECTED]> wrote: >> Hi, >> >> I wrote the 'autoimp' module [1], which allows you to import lazy modules: >> >> from autoimp import * (Import lazy wrapper objects around all modules; >> "lazy >>modules" will turn into normal modules when an >> attribute >>is first accessed with getattr()). >> from autoimp import A, B (Import specific lazy module wrapper objects). >> >> The main point of autoimp is to make usage of the interactive Python prompt >> more productive by including "from autoimp import *" in the PYTHONSTARTUP >> file. > > And it does. Gets rid of "oops, I forgot to import that module" > moments without cluttering my $PYTHONSTARTUP file with imports. +1. > > My only complaint is that it breaks globals(). And startup takes quite long the first time, because a list of all available modules must be gathered. To work around that, one can either use a special importing "lib" object, defined like that: class _lib: def __getattr__(self, name): return __import__(name) lib = _lib() or modify the globals() to automatically look up modules on KeyError, like this (put into PYTHONSTARTUP file): import sys, code class LazyImpDict(dict): def __getitem__(self, name): try: return dict.__getitem__(self, name) except KeyError: exc = sys.exc_info() try: return __import__(name) except ImportError: raise exc[0], exc[1], exc[2] d = LazyImpDict() code.interact(banner='', local=d) sys.exit() Of course, this is not perfect as it may break quite a lot of things, I haven't tested it thoroughly. Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: operator overloading + - / * = etc...
Tim Chase wrote: >>> Can these operators be overloaded? >> >> Yes. > > With the caveat of the "=" mentioned in the subject-line (being > different from "==")...I haven't found any way to override > assignment in the general case. There might be some oddball way > to do it via property() but AFAIK, this only applies to > properties of objects, not top-level names/variables. I'd love > to know if there's some workaround for this though... In almost all cases, binding a name cannot be overridden. There is a possibility to do that with globals, provided you do exec code in globals_dict where globals_dict is an instance of a subclass of dict that has a customized __setitem__. Georg -- http://mail.python.org/mailman/listinfo/python-list
