[issue38198] Attributes of pathlib classes are not indexed in Windows help file

2019-09-17 Thread Francesco Ricciardi


New submission from Francesco Ricciardi :

Attributes of pathlib classes (e.g. 'stem' or 'root') cannot be searched for in 
Python Windows help file index.

--
assignee: docs@python
components: Documentation
messages: 352630
nosy: docs@python, francescor
priority: normal
severity: normal
status: open
title: Attributes of pathlib classes are not indexed in Windows help file
type: enhancement
versions: Python 3.7

___
Python tracker 
<https://bugs.python.org/issue38198>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue37332] Python from Windows Store cannot install pycrypto

2019-06-18 Thread Francesco Mantovani


New submission from Francesco Mantovani :

Hello, 

I have installed Python 3.7 from the Windows Store, I was sure I was going to 
experience some trouble :)

In fact I was able to install Crypto (pip install Crypto) but I receive this 
error every time I run pip install pycrypto: (see log in attach).

Is evident that probably no user has access to 'C:\Program 
Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1008.0_x64__qbz5n2kfra8p0\python.exe'
 but why I was able to install Crypto? 

Anyway, I hope my feedback helps you

--
components: Installation
files: log.txt
messages: 346006
nosy: Francesco Mantovani
priority: normal
severity: normal
status: open
title: Python from Windows Store cannot install pycrypto
type: compile error
versions: Python 3.7
Added file: https://bugs.python.org/file48427/log.txt

___
Python tracker 
<https://bugs.python.org/issue37332>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



I wrote my very basic mkdocs plugin, hoping that it will inspire you to write your owns

2018-04-23 Thread francesco . maida
I wanted to write mkdocs plugins, so I read the docs (well, at least part of 
them) and I wrote a very simple, very basic plugin.
I called it "Hello dolly", because when I wrote it I was inspired by the (once 
built-in) WordPress plugin of the same name that teached me the basic of plugin 
writing for that blog platform.

It does a very simple, very basic tasks. In each document, the plugin looks for 
the specific tag {{dolly}} and replaces it with a random line from the "Hello 
dolly!" lyrics; I tried to keep the code as simple as possible, so you won't 
find any unit-testing code and even the search and replace part was done by 
using the str.replace method instead of using a regular expression.
I tried to comment the code whenever possible, but english is not my native 
language and you're likely to find a lot of grammar mistakes and typos in my 
comments, but I hope that my code will speak better than my own words.


If, like me, you're looking forward writing your own plugin then you might find 
useful to have a look at it.
You'll find it here:

https://github.com/fmaida/hello-dolly-mkdocs-plugin


If you have any questions, please contact me on GitHub and I'll try to help you.


Thank you for your time and best regards
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: unittest.Testsuite and execution order

2018-04-19 Thread Francesco Russo
On 18/04/18 20:26, Chris Angelico wrote:
> On Thu, Apr 19, 2018 at 2:51 AM, Francesco Russo <francesco...@gmail.com> 
> wrote:
>> My use case: my SUT is split into modules. Besides writing unit tests for
>> each module, I want to write an integration test, and I also need to
>> perform some actions between two calls to the SUT. In my case, the order of
>> the execution is important.
> 
> In that case, make these tests into a single test. If you have to do
> the steps together to correctly test it, they're not separate tests,
> they're separate parts of the same test.

Clear, thank you.

>> class MyTestCode(unittest.TestCase):
>>def test_func_1(self):
>>   # do something to test func_1 on the SUT
>>   sut.func_1()
>>   self.assert(...)
>>
>>def perform_intermediate_step(self):
>>   # do something between func_1 and func_2
>>
>>def test_func_2(self):
>>   # do something to test func_2 on the SUT
>>   sut.func_2()
>>   self.assert(...)
> 
> This is a bad idea. Each function that starts test_ should be
> completely independent. You should be able to run any one of them on
> its own (say, if you're trying to figure out why your latest change
> caused a test failure), and it should have the same result.
> 
> Make it so that test_func_1 and test_func_2 are completely
> independent, and then, if you need a single test that uses both, have
> a test that calls on each function.

I'm not sure I understand you here.
I understood that (besides, or instead of, making an integration test by
making those tests into one test, as you wrote above) I could make a
test for func_2 making it independent from func_1, for example this way:

class MyTestFunc2(unittest.TestCase):
   def setUp(self):
  # Prepare preconditions for func_2

   def test_func_2(self):
  sut.func_2()
  self.assert(...)

Such a test case wouldn't even need a test suite.
Is this what you meant?

>> Such an example works, today, since TestSuite uses a list, and addTest()
>> appends to the list.
>> My question is: is this something that I can rely on for the future? I
>> definitely don't want to rely on the current implementation, unless I see
>> it in the documentation.
> 
> I would say no, you can't rely on it. If you can't find it in the
> docs, don't assume it's true. Test order randomization can be
> controlled with a simple command line flag.
> 
> ChrisA

The official "unittest" web pages for Python 2 and 3 say this, for the
TestSuite class:
*This class represents an aggregation of individual tests cases and test
suites*
saying nothing about the order. But the docstring of the TestSuite class
says:
*It will run the individual test cases in the order in which they were
added, aggregating the results*
Can I consider the docstring an official documentation as well?

-- 
Francesco Russo
The White Rabbit put on his spectacles. 'Where shall I begin, please
your Majesty?' he asked.
'Begin at the beginning,' the King said gravely, 'and go on till you
come to the end: then stop.'
-- 
https://mail.python.org/mailman/listinfo/python-list


unittest.Testsuite and execution order

2018-04-18 Thread Francesco Russo
Hello!

I'm reading the documentation of unittest.TestSuite (Python 2 and 3), but I
can't find any explicit sentence stating that TestSuite will honor the
order. I can only read that TestSuite can group test cases together. Please
blame it on my poor English skills if I'm not interpreting the
documentation correctly.

My use case: my SUT is split into modules. Besides writing unit tests for
each module, I want to write an integration test, and I also need to
perform some actions between two calls to the SUT. In my case, the order of
the execution is important.

Now, the current implementation of TestSuite uses a list, internally, so,
today, the order is honored if I create a TestSuite calling addTest() in
the proper order, or if I pass a list to the constructor. I've seen
examples like this:

class MyTestCode(unittest.TestCase):
   def test_func_1(self):
  # do something to test func_1 on the SUT
  sut.func_1()
  self.assert(...)

   def perform_intermediate_step(self):
  # do something between func_1 and func_2

   def test_func_2(self):
  # do something to test func_2 on the SUT
  sut.func_2()
  self.assert(...)

suite = unittest.TestSuite()
suite.addTest(MyTestCode("test_func_1"))
suite.addTest(MyTestCode("perform_intermediate_step"))
suite.addTest(MyTestCode("test_func_2"))

Such an example works, today, since TestSuite uses a list, and addTest()
appends to the list.
My question is: is this something that I can rely on for the future? I
definitely don't want to rely on the current implementation, unless I see
it in the documentation.

If it's something that I can't rely on for the future, then I'd rather
write my test code in a different way.

Regards,
Francesco

P.S.: I strongly believe that there are better ways to implement a test
like the one I just described, but what I'm interested in now is whether
TestSuite is meant to be future-proof for such a case.

-- 
Francesco Russo
The White Rabbit put on his spectacles. 'Where shall I begin, please your
Majesty?' he asked.
'Begin at the beginning,' the King said gravely, 'and go on till you come
to the end: then stop.'
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue31797] Python 3.6.3: JSON loop fails using elif

2017-10-16 Thread Francesco Mantovani

New submission from Francesco Mantovani <francesco84mantov...@gmail.com>:

I attach here a file with 3 different way to parse Google Places API.

Please put your Google API key token into the variable 
[PutHereYourGoogleAPIKey] to make the script work.

The script contains 3 loops:
- the first loop works and that's how I fixed the problem 
- the second loop fail because of the `elif`
- the third loop works because all `elif` were removed

--
components: Interpreter Core
files: Test_log_bug.py
messages: 304465
nosy: Francesco Mantovani
priority: normal
severity: normal
status: open
title: Python 3.6.3: JSON loop fails using elif
type: behavior
versions: Python 3.6
Added file: https://bugs.python.org/file47222/Test_log_bug.py

___
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue31797>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue28851] namedtuples field_names sequence preferred

2016-12-01 Thread Francesco Grondona

New submission from Francesco Grondona:

A change by mhettinger in the doc of Python 2 years ago implicitely stated a 
sequence of strings as preferred way to provide 'field_names' to a namedtuple:

https://github.com/python/cpython/commit/7be6326e09f2062315f995a18ab54baedfd0c0ff

Same change should be integrated in Python 3, I see no reason to prefer the 
single string version.

--
assignee: docs@python
components: Documentation
messages: 282177
nosy: docs@python, peentoon
priority: normal
severity: normal
status: open
title: namedtuples field_names sequence preferred
type: enhancement
versions: Python 3.3, Python 3.4, Python 3.5, Python 3.6, Python 3.7

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue28851>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: What should a decorator do if an attribute already exists?

2016-05-16 Thread Francesco Loffredo

On 10/05/2016 17:45, Steven D'Aprano wrote:

I have a decorator that adds an attribute to the decorated function:


def decorate(func):
 instrument = make_instrument()

 @functools.wraps(func)
 def inner(*args):
 instrument.start()
 result = func(*args)
 instrument.finish()
 return result

inner.instrument = instrument
return inner


The actual nature of the instrumentation isn't important: depending on the
decorator, it might count the number of function calls made, how long it
takes, count cache hits, or something else.

My question is, what should I do if the decorated function already has an
instrument attribute?

1. raise an exception?

2. raise a warning, and over-write the attribute?
3. raise a warning, and skip adding the attribute?
4. raise a warning, and rename the existing instrument to
something else before writing my own instrument?

5. silently over-write the attribute?


I think 5 is clearly wrong, 4 is too difficult, and 3 seems pointless. So I
think either 1 or 2 is the right thing to do.

Thoughts?

CAVEAT: I speak out of utter ignorance, please don't slap me if i'm 
saying something blatantly stupid...


From your example, it seems that you use your instrument only inside 
your decorator. So I think "instrument" could be a "private variable".


What if you called your instrument "__instrument", taking advantage of 
name mangling?
This would, IMHO, solve entirely the name clash problem, and you could 
even access your instrument from outside, using its "mangled" name.
This, of course, leads to another question: what happens to name 
mangling in a decorator? What will be actually called the variable 
"__instrument"?


And what happens if you want to add another instrument, decorating the 
target twice?


Francesco
--
https://mail.python.org/mailman/listinfo/python-list


[issue26197] arange from numpy function has some limits....I propose a python function that overcome these limitations

2016-01-25 Thread Francesco Pelizza

Changes by Francesco Pelizza <francesco.pelizza.un...@gmail.com>:


--
title: arange from numpy function has some limitsI propose a python 
function that overcome -> arange from numpy function has some limitsI 
propose a python function that overcome these limitations

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue26197>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue26197] arange from numpy function has some limits....I propose a python function that overcome

2016-01-25 Thread Francesco Pelizza

New submission from Francesco Pelizza:

arange from numpy is a function to generate list of floats from a start to an 
end number with a defined float number.

The "arange" function works fine for some cases, but in my case where I have to 
generate numbers that constitute parameters in a Quantum Mechanical 
calculation, numbers can be missing or be more than what I want, since many 
time each number is calculated in a couple of days or more. I need to avoid 
extra numbers or missing numbers to avoid loss of data. And sometimes the 
script will pass to a cycle function wrong numbers for start and stop, or the 
same number as starting and ending point, but I can not avoid this because they 
are numbers coming from Quantum World, and I need a function that sort out 
anything on its own because is inserted in for loops and things like that.

Also arange function does not take the "stop" number as the last number of the 
list, but it will terminate before, so to have the last wanted number in the 
list you have to use the formulae  arange(start,stop+inc,inc) or 
arange(start,stop+n,inc) where n allows is bigger than zero.

Some cases that give me problems are the following:
Defective lists of numbers:
1) arange(1,10+0.001,0.0001) some numbers are missing
2) arange(1,10+0.001,1) generate float without any decimal after the point
3) arange(1,10,0.001) some numbers are missing
4) ...other combination gives problems

Empty lists of numbers:
1) arange(1,10,-1)
2) arange(1,-10,1)
3) arange(1,1,1)
4) arange(1,1,0.5)
5) arange(1,-10,0.005)
6) so on

I made a python function that goes across any of these problems, taking account 
of using the absolute value of the given incremental step number.

Numbers can be float or integers, any exception of number ordering is kept 
under control to generate anyway at least a list of one number, if the stop 
number is bigger than the starting one, they get switched to generate anyway a 
list of numbers. And it can go down until 14 decimal places of incremental 
steps without generating wrong numbers due to the binary conversion of floats!
Some use of this function are eventually weird or really exotic, but in using 
python as a code to deal with computation without crashing for silly numbers 
ordering from the quantum world, is essential.

Do you agree with the improvements I put in this function called "CYCLE" can be 
of help?

I would like to share it with the community.

Here attached the function I made

--
components: Library (Lib)
files: CYCLE.py
messages: 258899
nosy: Francesco Pelizza
priority: normal
severity: normal
status: open
title: arange from numpy function has some limitsI propose a python 
function that overcome
type: enhancement
versions: Python 2.7
Added file: http://bugs.python.org/file41707/CYCLE.py

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue26197>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue25453] Arithmetics with complex infinities is inconsistent with C/C++

2015-10-22 Thread Francesco Biscani

Francesco Biscani added the comment:

@Mark

Yes I understand that this is a thorny issue. I was kinda hoping NumPy would 
just forward complex arithmetic to the underlying C implementation, but 
apparently that's not the case (which OTOH makes sense as the use of C99 
complex numbers is not that widespread).

FWIW, the quoted section in the C standard (Annex G) contains the pseudocode 
for standard-conforming implementations of complex multiplication and division, 
in case the decision is taken to change the behaviour.

--

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue25453>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue25453] Arithmetics with complex infinities is inconsistent with C/C++

2015-10-21 Thread Francesco Biscani

Francesco Biscani added the comment:

The best reference I could find so far is in the C99 standard:

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf

Annex G is titled "IEC 60559-compatible complex arithmetic". In G.3.1 it is 
written:

"""
A complex or imaginary value with at least one infinite part is regarded as an 
infinity (even if its other part is a NaN).
"""

Later on, in G.5.1.4, it is stated:

"""
The * and / operators satisfy the following infinity properties for all real, 
imaginary, and complex operands:

- if one operand is an infinity and the other operand is a nonzero finite 
number or an infinity, then the result of the * operator is an infinity;
- if the first operand is an infinity and the second operand is a finite 
number, then the result of the / operator is an infinity;
- if the first operand is a finite number and the second operand is an 
infinity, then the result of the / operator is a zero;
"""

So to recap, according to these definitions:

- inf + nanj is a complex infinity,
- (inf + nanj) * (2 + 0j) should give a complex infinity (i.e., a complex 
number in which at least one component is inf).

I am not saying that these rules are necessarily "mathematically correct". I am 
aware that floating point is always a quagmire to get into, and the situation 
here is even more complex (eh!) than usual.

But it seems to me that Python, or CPython at least, follows a pattern of 
copying (or relying on) the behaviour of C for floating-point operations, and 
it seems like in the case of complex numbers this "rule" is broken. It 
certainly caught me by surprise anyway :)

--

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue25453>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue25453] Arithmetics with complex infinities is inconsistent with C/C++

2015-10-21 Thread Francesco Biscani

Francesco Biscani added the comment:

Hi Mark,

the original code is C++, and the inf + nanj result can be reproduced by the 
following snippet:

"""
#include 
#include 

int main(int argc, char * argv[]) {
  std::cout << std::complex(3,0) / 0. << '\n';
  return 0;
}
"""

Here is the C99 version:

"""
#include 
#include 
#include 

int main(int argc, char * argv[]) {
  double complex a = 3.0 + 0.0*I;
  printf("%f + i%f\n", creal(a/0.), cimag(a/0.));
  return 0;
}
"""

This is on Linux x86_64 with GCC 4.9. Clang gives the same result. Adding the 
"-ffast-math" compilation flag changes the result for the C version but 
apparently not for the C++ one.

The original code came from an implementation of a special function f(z) which 
has a pole near the origin. When computing f(0), the C++ code returns 
inf+nan*j, which is fine (in the sense that it is a complex infinity of some 
kind). I then need to use this result in a larger piece of code which at one 
point needs to compute 1/f(0), with the expected result being 0 mathematically. 
This works if I implement the calculation all within C/C++, but if I switch to 
Python when computing 1/f(0) I get nan + nan*j as a result.

Of course I could do all sorts of stuff to improve this specific calculation 
and avoid the problems (possibly improving the numerical behaviour near the 
pole via a Taylor expansion, etc. etc. etc.).

Beware that implementing C99 behaviour will result in a noticeable overhead for 
complex operations. In compiled C/C++ code one usually has the option to switch 
on/off the -ffast-math flag to improve performance at the expense of 
standard-conformance, but I imagine this is not feasible in Python.

--

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue25453>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue25453] Arithmetics with complex infinities is inconsistent with C/C++

2015-10-21 Thread Francesco Biscani

New submission from Francesco Biscani:

The C++11/C99 standards define a complex infinity as a complex number in which 
at least one of the components is inf. Consider the Python snippet:

>>> complex(float('inf'),float('nan'))*2
(nan+nanj)

This happens because complex multiplication in Python is implemented in the 
most straightforward way, but the presence of a nan component "infects" both 
components of the result and leads to a complex nan result. See also how 
complex multiplication is implemented in Annex G.5.1.6 of the C99 standard.

It feels wrong that a complex infinity multiplied by a real number results in a 
complex nan. By comparison, the result given here by C/C++ is inf+nan*j.

Note also this:

>>> complex(float('inf'),float('nan'))+2  
(inf+nanj)

That is, addition has a different behaviour because it does not require mixing 
up the components of the operands.

This behaviour has unexpected consequences when one interacts with math 
libraries implemented in C/C++ and accessed via Python through some wrapping 
tool. For instance, whereas 1./(inf+nan*j) is zero in C/C++, it becomes in 
Python

>>> 1./complex(float('inf'),float('nan'))  
(nan+nanj)

--
messages: 253283
nosy: Francesco Biscani
priority: normal
severity: normal
status: open
title: Arithmetics with complex infinities is inconsistent with C/C++
type: behavior
versions: Python 2.7, Python 3.3

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue25453>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Python declarative

2014-01-19 Thread Francesco Bochicchio
Looking at my own code after four years, I just realized that most of 
parentheses can be avoided by redefining the += operators to be a synonym of 
the add method.

Go figure, I guess that with age it _does_ come a little wisdom ... :-)

Ciao
-
FB
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python declarative

2014-01-17 Thread Francesco Bochicchio
Some time ago I played with Tkinter trying a more declarative way of coding the 
GUI building part and I come out with this:

   top = Tk( 'top' ).add (
 Frame( 'frame' ).add (
Pack( side = 'top' ),
Frame ( 'panel1' ).add (
Pack( side='left'),
Label ( 'label', text=Entry 1 :  ),
Entry ( 'entry' )  
),
Frame( 'panel2' ).add (
Pack( side='left'),
Label ( 'label', text=Entry 2 :  ),
Entry( 'entry' ) 
),
Pack( side = 'bottom' ), # packing change 
Button( 'button', 
text='Click Me' ))
 )

top.frame.button[command] = functools.partial(button_cb, top)
top.realize().mainloop()

which, without changing the underlying plumbing, may also be written this way, 
which avoid nesting but still looks  declarative-ish :

   top = Tk( 'top' )
top.add( Frame( 'frame' ) )
top.frame.add (
Pack( side = 'top' ),
Frame ( 'panel1' ),
Frame( 'panel2' ),
Pack( side = 'bottom' ), # packing change 
Button( 'button', 
text='Click Me',
command = functools.partial(button_cb, top) ) )

top.frame.panel1.add(
Pack( side='left'),
Label ( 'label', text=Entry 1 :  ),
Entry ( 'entry' ) ) 

top.frame.panel2.add(
Pack( side='left'),
Label ( 'label', text=Entry 1 :  ),
Entry( 'entry' )  ) 
   
top.realize().mainloop()


The underlying plumbing for those two examples is just two classes amounting to 
about fifty lines of code, plus one-liner wrappers for each kind of 
widgets/geometry

This just to tell you that yes, with python you can write declarative-looking 
code ... if you don't mind parenthesis :-)
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue17528] Implement dumps/loads for lru_cache

2013-03-23 Thread Francesco Frassinelli

New submission from Francesco Frassinelli:

Hi,
I propose to change the public API of functools.lru_cache in order to make the 
cache persistent when the program is restarted.
It could be implemented using two different functions (dumps/loads), where the 
cached is exported into a classical dictionary and restored in the same way.
A third argument could be also added to provide the initial cache (calling the 
loads function internally after the initialization).

I think this could be an important enhancement because lru_cache will probably 
implemented in C and try to export cache contents it will be not possible (see: 
http://bugs.python.org/issue14373).

--
messages: 185036
nosy: frafra
priority: normal
severity: normal
status: open
title: Implement dumps/loads for lru_cache
type: enhancement

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue17528
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



lpod-python

2012-08-10 Thread Francesco
I'm trying to use the lpod-python module to programmatically read data from Open Document files. My problem is: i can't download the 
module from its authors' site, http://download.lpod-project.org/lpod-python/lpod-python-0.9.3.tar.gz. It seems the download site is 
unavailable, while the main site is working.

I also tried to install the module with pip (I read on the site that it's now 
available), but again, no luck.
Do somebody know what's happening to download.lpod-project.org ? It doesn't 
even ping...

Please let me know, thank you very much.
Francesco
--
http://mail.python.org/mailman/listinfo/python-list


EuroPython 2012: Call for Proposal is Open! [Please spread the word]

2012-03-01 Thread Francesco Pallanti
Hi guys,
I'm Francesco and I am writing on behalf of EuroPython Staff
(www.europython.eu). We are happy to announce that the Call for
Proposals is now officially open! 

DEADLINE FOR PROPOSALS: MARCH 18TH, 23:59:59 CET

For those who have never been at EuroPython (or similar conferences)
before, the Call for Proposals is the period in which the organizers ask
the community to submit proposals for talks to be held at the
conference.

Further details about Call for Proposal are online here:
http://ep2012.europython.eu/call-for-proposals/

EuroPython is a conference run by the community for the community: the
vast majority of talks that are presented at the conference will be
proposed, prepared and given by members of the Python community itself.

And not only that: the process that selects the best talks among all the
proposals will also be public and fully driven by the community: it's
called Community Voting, and will begin right after the Call for
Proposals ends.

CFP: Talks, Hands-On Trainings and Posters
--

We're looking for proposals on every aspect of Python: programming from
novice to advanced levels, applications and frameworks, or how you have
been involved in introducing Python into your organisation.

There are three different kind of contribution that you can present at
EuroPython:
- Regular talk. These are standard talk with slides, allocated in
slots of 45, 60 or 90 minutes, depending on your preference and
scheduling constraints. A QA session is held at the end of the talk.
- Hands-on training. These are advanced training sessions for a smaller
audience (10-20 people), to dive into the subject with all details.
These sessions are 4-hours long, and the audience will be strongly
encouraged to bring a laptop to experiment. They should be prepared with
less slides and more source code.
- Posters. Posters are a graphical way to describe a project or a
technology, printed in large format; posters are exhibited at the
conference, can be read at any time by participants, and can be
discussed face to face with their authors during the poster session. We
will take care of printing the posters too, so don't worry about
logistics.

More details about Call for Proposal are online here:
http://ep2012.europython.eu/call-for-proposals/

Don't wait for the last day
---

If possible, please avoid submitting your proposals on the last day. It
might sound a strange request, but last year about 80% of the proposals
were submitted in the last 72 hours. This creates a few problems for
organizers because we can't have a good picture of the size of the
conference until that day.

Remember that proposals are fully editable at any time, even after the
Call for Proposals ends. You just need to login on the website, go to
the proposal page (linked from your profile page), and click the Edit
button.

First-time speakers are especially welcome; EuroPython is a community
conference and we are eager to hear about your experience. If you have
friends or colleagues who have something valuable to contribute, twist
their arms to tell us about it!

We are a conference run by the community for the community. Please help
to spread the word by distributing this announcement to colleagues,
mailing lists, your blog, Web site, and through your social networking
connections. 

All the best,


-- 
Francesco Pallanti - fpalla...@develer.com
Develer S.r.l. - http://www.develer.com/
.software  .hardware  .innovation
Tel.: +39 055 3984627 - ext.: 215

-- 
http://mail.python.org/mailman/listinfo/python-list


Deleted System default Python on Leopard

2012-01-16 Thread Francesco Zhu

Hello everyone,

recently I've started to be try Python on my Mac OS X 10.5.8 Leopard and I've 
already messed up with it...

I was compiling a Python souce code but didn't succeed and so I decided to 
install a newer version of Python.
But before that, I did a stupid thing: I deleted manually all the folders of 
the Leopard's system default Python 2.5.1...

Before when I was using the system Python, the program namebench worked 
perfectly.
After that I messed everything up and installed MacPython 2.5 from the site 
python.org, now namebench always crashes.

On the problem report system of Apple it gives me these errors:
http://bpaste.net/show/21904/

While this is the Console:
http://bpaste.net/show/21905/

What problem can it be?
Can I clean up all the Pythons and restore the system one?

Thanks everyone.

Regards,
Francesco Zhu
  -- 
http://mail.python.org/mailman/listinfo/python-list


Re: I love the decorator in Python!!!

2011-12-09 Thread Francesco Bochicchio
On 8 Dic, 12:22, K.-Michael Aye kmichael@gmail.com wrote:
 On 2011-12-08 08:59:26 +, Thomas Rachel said:



  Am 08.12.2011 08:18 schrieb 8 Dihedral:
  I use the @ decorator to behave exactly like a c macro that
  does have fewer side effects.

  I am wondering is there other interesting methods to do the
  jobs in Python?

  In combination with a generator, you can do many funny things.

  For example, you can build up a string:

  def mkstring(f):
       Turns a string generator into a string,
       joining with , .
       
       return , .join(f())

  def create_answer():
       @mkstring
       def people():
           yield Anna
           yield John
           yield Theo

       return The following people were here:  + people

  Many other things are thinkable...

  Thomas

 I am still perplexed about decorators though, am happily using Python
 for many years without them, but maybe i am missing something?
 For example in the above case, if I want the names attached to each
 other with a comma, why wouldn't I just create a function doing exactly
 this? Why would I first write a single name generator and then decorate
 it so that I never can get single names anymore (this is the case,
 isn't it? Once decorated, I can not get the original behaviour of the
 function anymore.
 So, above, why not
 def mkstring(mylist):
 with the same function declaration and then just call it with a list of
 names that I generate elsewhere in my program?
 I just can't identify the use-case for decorators, but as I said, maybe
 I am missing something.

 Michael

I had/have similar feelings. For instance,  this is something that I
tought useful, but then I never used in real code.
The idea was to find a way to automate this code pattern, which I do a
lot:

class SomeClass:
   def __init__(self, some, attribute, here ):
   self.some, self.attribute, self.here = some, attribute, here


In other words, I often define classes in which the constructor list
of arguments corresponds one-to-one to class attributes.
So I thought of this (it uses class decorators so it only works with
Python 3.x ) :


class FieldsDecorator:
def __init__(self, *names):
self.names = names

def __call__(self, cls):
def constructor(instance, **kwds):
for n,v in kwds.items():
if n in self.names:
setattr(instance, n, v)
else: raise TypeError(%s is not a valid field % s )
setattr(cls, '__init__', constructor )
return cls


@FieldsDecorator(uno, due)
class Prova:
pass

p = Prova(uno=12, due=9)
print (p.uno, p.due )


It works and it is nice, but I don't find it compelling enough to use
it. I keep assigning directly the attributes, which is more readable.

Decorators are really useful when you have lot of repetitive
boilercode that you _want_ to hide,  since it has little to do with
the problem logic and more to to with the technicalities of the
programming language or of some framework that you are using. It is
called separating of concerns I think, and is one of the principles
of Aspect-Oriented Programming (and  with decorators you can do some
nice AOP exercises ... ).

Ciao
---
FB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Maximize already running tkinter program on invocation

2011-07-27 Thread Francesco Bochicchio
On 27 Lug, 10:18, Steven Kauffmann steven.kauffm...@gmail.com wrote:
 Hi all,

 I have written a small GUI application in python 3.x using the tkinter
 module. Program is running fine, but multiple instances of the program
 can now be created. I would like to reduce the number of instances of
 the program to only 1 instance. I know that this is possible by using
 a singleton class. This way it's possible to check if the program is
 already running or not.

 When I invoke the program and it detects that the program is already
 running, is it then possible to maximize the already running program?

 I can find a lot of examples about singleton classes in python on the
 web, but nothing about showing the already running application when 1
 instance of the program already exists. Is there a way to realize this
 in python?

 I'm now doing the development on a linux machine, but the final
 program should work on Windows.

 Cheers,


The multiprocesing  module could help you in making sure that two
instances of the same program are not started ( for instance using
multiprocessing.Queue) as well as to signal the already running
instance that it sould maximize its window ( for instance using
multiprocessing.Queue ). Just make sure that what you use is supoorted
on your target operating system(s).

However, the integration of any form of inter-process communication
with Tkinter main loop is going to be tricky ...


Ciao
-
FB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Square bracket and dot notations?

2011-06-11 Thread Francesco Bochicchio
On 11 Giu, 11:41, Asen Bozhilov asen.bozhi...@gmail.com wrote:
 Hi all,
 I am beginner in Python. What is interesting for me is that Python
 interpreter treats in different way dot and square bracket notations.
 I am coming from JavaScript where both notations lead prototype chain
 lookup.

 In Python it seems square bracket and dot notations lead lookup in
 different store.

 Simple example with dict object:

 d = {key : value}

 print d[key] #value

 print d.key #AttributeError

 I found an implementation of dict which uses both notations for its
 keys lookup, which I think is stupid idea when obviously both
 notations lead different lookup. It will confuse me as a reader of the
 code.

 Anyway, I would like to know more about the lookup for key of dict and
 lookup for property of any object with dot notation. Any materials and
 explanations are highly appreciated.

Since python is not javascript ( duh :-), [] and . notations are used
for different purposes and, although
they share some commonalities as I try to show later in this post,
they should not be intermixed without
a very good reeason ( and it's cool is not a good reason IMO).

Broadly speaking, square brackets are used to access element in array,
dict, tuples and sequences.
The dot nootation is used to get the attributes and methods of
instances.

User classes - that is the ones you define with the class statement -
can implement support for the squared bracket and
dot notations:
-  the expression myinstance[index] is sort of translated into  of
myinstance.__getitem__(index)
-   the expression myinstance.myattribute is sort of translated of
myinstance.__getattr__(myattribute)

Classes also exposes a __dict__ attributes that allows to access to
instance attributes and methods using dictionary
semantics. That is, myistance.__dict__[myattribute]  should give the
same result as  myinstance.myattribute.
I believe this is because in the beginning class instances actually
had a dictionary storing the instance attributes.
Nowadays it is more complex than that, I think,  but the interface is
kept to allow dynamic access to instance contents,
although the reccomended way to do it this is getattr(myinstance,
myattribute). Of course it is only useful to use __dict__
or getattr when the parameter is not a constant string but a variable
referring to a string computed at run time  (  this is
what I mean for 'dynamic access' ).

HTH.


Ciao

FB

-- 
http://mail.python.org/mailman/listinfo/python-list


[issue10042] total_ordering

2011-04-21 Thread Francesco Ricciardi

Francesco Ricciardi francescor2...@yahoo.it added the comment:

On the one hand, it's not just a matter of total_ordering and rich comparison 
operators, because all user defined operators may return NotImplemented when 
they get types that they don't know how to handle.

On the other hand, if such a decision is taken, a long path should be planned 
to move handling of unknown types from one way to the other.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue10042
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue10042] total_ordering

2011-04-20 Thread Francesco Ricciardi

Francesco Ricciardi francescor2...@yahoo.it added the comment:

I think the whole issue is indeed how NotImplemented is treated. To me saying 
that 'not NotImplemented' is True is wrong. About the stack overflow I found 
there are various possible fixes, however none will nice.

By definition, NotImplemented is the way that a method or operation have to 
signal to the interpreter that it doesn't know how to handle given operand 
types. IMHO, it shouldn't be possible to receive NotImplemented as operand 
value, and it shouldn't have a boolean value. Indeed, t should be handled as a 
special case by the interpreter.

To go further, I am not really sure that NotImplemented should be a return 
value. Probably, an exception that is trapped by the interpreter when 
evaluating an expression would be easier to define and handle.

Of course, such a change should be deeply grokked before being put in place, 
also because of the high impact on code that already relies on NotImplemented 
having a value.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue10042
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Is there any python library that parse c++ source code statically

2011-03-13 Thread Francesco Bochicchio
On 13 Mar, 10:14, kuangye kuangye19840...@gmail.com wrote:
 Hi, all. I need to generate other programming language source code
 from C++ source code for a project. To achieve this, the first step is
 to understand the c++ source code at least in formally. Thus is
 there any library to parse the C++ source code statically. So I can
 developer on this library.

 Since the C++ source code is rather simple and regular. I think i can
 generate other language representation from C++ source code.


The problem is that C++ is a beast of a language and is not easy to
find full parsers for it.
I've never done it, but sometime I researched possible ways to do it.
The best idea I could come with
is doing it in 2 steps:

 - using gcc-xml ( http://www.gccxml.org/HTML/Index.html ) to generate
an xml representation of the code
 - using one of the many xml library for python to read the xml
equivalent of the code and then generate the equivalent
   code in other languages ( where you could use a template engine,
but I found that the python built-in string
   formatting libraries are quite up to the task ).

HTH

Ciao
---
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiple values for keyword argument

2011-01-29 Thread Francesco Bochicchio
On 29 Gen, 12:10, Tobias Blass tobiasbl...@gmx.net wrote:
 Hi all
 I'm just learning python and use it to write a GUI (with Tkinter) for a C
 program I already wrote. When trying to execute the program below I get the
 following error message.

 Traceback (most recent call last):
   File ./abirechner.py, line 64, in module
       win =MainWin()
   File ./abirechner.py, line 43, in __init__
       self.create_edit(row=i);
 TypeError: create_edit() got multiple values for keyword argument 'row'

 I don't really understand why create_edit gets multiple values, it gets one
 Integer after another (as I see it)
 Thanks for your help

 abirechner.py:

 # line 37
 class MainWin(Frame):
         def __init__(self,master=None):
                 Frame.__init__(self,master)
                 self.grid()
                 self.edits=()
                 for i in range(10):
                         self.create_edit(row=i);
         def create_edit(row,self):
                 # LineEdit is defined, but I don't consider it important here
                 self.edits+=LineEdit()
                 self.edits[-1].grid(row=row,column=0)
 # ...
 #line 64
 win = MainWin()
 win.mainLoop()

Try this:

 def create_edit(self, row):

Ciao
---
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


python only prints integers

2011-01-06 Thread francesco
I'm pretty new in Python language. I have a problem with numbers: it
seems python doesn't know any more how to count!
I get only the down rounded integer
20/8 = 2
8/3=2
I probably changed some option to round the numbers, but I don't
remember how.
Is there a way to reset the number of digits to default?
Thanks in advance
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python only prints integers

2011-01-06 Thread francesco
On 6 Gen, 23:59, Ian ian.g.ke...@gmail.com wrote:
 On Jan 6, 3:49 pm, francesco cerutti.francesco...@gmail.com wrote:

  I'm pretty new in Python language. I have a problem with numbers: it
  seems python doesn't know any more how to count!
  I get only the down rounded integer
  20/8 = 2
  8/3=2
  I probably changed some option to round the numbers, but I don't
  remember how.
  Is there a way to reset the number of digits to default?

 In Python 2, the '/' operator performs integer division by default
 when both its operands are integers.  To change this, either place
 this at the top of the file:

 from __future__ import division

 or convert your numbers to floats:

  20.0 / 8.0
 2.5
  float(20) / float(8)

 2.5

 In Python 3, the '/' operator always performs true division.

Thanks to all! Very quick answer!
I fixed the problem by using floats.
Thanks again
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: while True or while 1

2010-12-28 Thread Francesco

hehehehehehe...

On 17/12/2010 2.01, Steven D'Aprano wrote:

On Thu, 16 Dec 2010 23:34:21 +, BartC wrote:


In terms of a more realistic function (admittedly still a little
contrived, as the loop would be written differently), I tried this:

def p2(n):
   p=1
   while True:
 if n=p: return p
 p=1
   return 0

for i in xrange(100):
   x=p2(i)

p2() calculates the smallest power of 2= it's operand.

Using while True as shown, it took 3.4 seconds. Using While 1, it took
2.6 seconds (Python 2.5).



Right. And a saving of 0.8 microseconds per iteration is a micro-
optimization which is likely to be invisible in any real situation.

I mean, yes, you saved almost an entire second. Wow. Save another 179 of
them and you'll almost have enough time to make yourself a coffee.

Bart, we get it. Nobody denies that the optimization is real, only that
it is generally meaningful. Who cares whether it takes 2 seconds or 4
seconds to generate one million results if the rest of the application
takes 3 minutes to run?

*If* your application is such that saving 0.8 microseconds per iteration
actually is useful, AND your loop has to be written as a while True loop,
then this *may* be a useful micro-optimization to save 0.8 microseconds
per iteration. That's a vanishingly tiny proportion of all code written.
If your code happens to meet those conditions, then by all means use
while 1. Or move to Python 3, where while True has the same
optimization performed.

But in general, such micro-optimizations are not terribly useful. If you
shave off 1 second off a program that runs in 3 seconds, chances are
nobody is even going to notice. Two seconds or three, who cares? Either
way, it's too short to do anything else, and not long enough to matter.
If you shave off an hour off a program that takes 20 hours, who is going
to care?

But so long as it doesn't introduce bugs, or make maintenance harder, or
add complexity, such micro-optimizations don't harm either.



HEY! That was MY argument! ;-))

Newsgroups: comp.lang.python
Subject: Re: If/then style question
Date: Tue, 21 Dec 2010 20:54:02 +0100

I'd bet you would stress your point Steven! But you don't need to persuade me, 
I do already agree.
I just meant to say that, when the advantage is little, there's no need to 
rewrite a working function.
And that with modern CPUs, if tests take so little time, that even some 
redundant one is not so much of a nuisance.
in your working example, the payload is just a couple of integer calculations, that take very little time too. So the overhead due 
to redundant if tests does show clearly. And also in that not-really-real situation, 60% overhead just meant less than 3 seconds. 
Just for the sake of discussion, I tried to give both functions some plough to pull, and a worst-case situation too:


 t1 = Timer('for x in range(100): print func1(0),',
...  'from __main__ import func1')

 t2 = Timer('for x in range(100): print func2(0),',
...  'from __main__ import func2')

 min(t1.repeat(number=1, repeat=1))
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1
53.011015366479114
 min(t2.repeat(number=1, repeat=1))
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1
47.55442856564332

that accounts for a scant 11% overhead, on more than one million tests per 
cycle.

That said,  let's make really clear that I would heartily prefer func2 to func1, based both on readability and speed. Thank you for 
having spent some time playing with me!

Francesco

On 19/12/2010 1.05, Steven D'Aprano wrote:
 Well, let's try it with a working (albeit contrived) example. This is
 just an example -- obviously I wouldn't write the function like this in
 real life, I'd use a while loop, but to illustrate the issue it will do.

 def func1(n):
  result = -1
  done = False
  n = (n+1)//2
  if n%2 == 1:
  result = n
  done = True
  if not done:
  n = (n+1)//2
  if n%2 == 1:
  result = n
  done = True
  if not done:
  n = (n+1)//2
  if n%2 == 1:
  result = n
  done = True
  if not done:
  for i in range(100):
  if not done:
  n = (n+1)//2
  if n%2 == 1:
  result = n
  done = True
  return result


 def func2(n):
  n = (n+1)//2
  if n%2 == 1:
  return n
  n = (n+1)//2
  if n%2 == 1:
  return n
  n = (n+1)//2
  if n%2

Re: If/then style question

2010-12-21 Thread Francesco

I'd bet you would stress your point Steven! But you don't need to persuade me, 
I do already agree.
I just meant to say that, when the advantage is little, there's no need to 
rewrite a working function.
And that with modern CPUs, if tests take so little time, that even some 
redundant one is not so much of a nuisance.
in your working example, the payload is just a couple of integer calculations, that take very little time too. So the overhead due 
to redundant if tests does show clearly. And also in that not-really-real situation, 60% overhead just meant less than 3 seconds. 
Just for the sake of discussion, I tried to give both functions some plough to pull, and a worst-case situation too:


 t1 = Timer('for x in range(100): print func1(0),',
...  'from __main__ import func1')

 t2 = Timer('for x in range(100): print func2(0),',
...  'from __main__ import func2')

 min(t1.repeat(number=1, repeat=1))
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1
53.011015366479114
 min(t2.repeat(number=1, repeat=1))
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1
47.55442856564332

that accounts for a scant 11% overhead, on more than one million tests per 
cycle.

That said,  let's make really clear that I would heartily prefer func2 to func1, based both on readability and speed. Thank you for 
having spent some time playing with me!

Francesco

On 19/12/2010 1.05, Steven D'Aprano wrote:

Well, let's try it with a working (albeit contrived) example. This is
just an example -- obviously I wouldn't write the function like this in
real life, I'd use a while loop, but to illustrate the issue it will do.

def func1(n):
 result = -1
 done = False
 n = (n+1)//2
 if n%2 == 1:
 result = n
 done = True
 if not done:
 n = (n+1)//2
 if n%2 == 1:
 result = n
 done = True
 if not done:
 n = (n+1)//2
 if n%2 == 1:
 result = n
 done = True
 if not done:
 for i in range(100):
 if not done:
 n = (n+1)//2
 if n%2 == 1:
 result = n
 done = True
 return result


def func2(n):
 n = (n+1)//2
 if n%2 == 1:
 return n
 n = (n+1)//2
 if n%2 == 1:
 return n
 n = (n+1)//2
 if n%2 == 1:
 return n
 for i in range(100):
 n = (n+1)//2
 if n%2 == 1:
 return n
 return -1


Not only is the second far more readable that the first, but it's also
significantly faster:


from timeit import Timer
t1 = Timer('for i in range(20): x = func1(i)',

... 'from __main__ import func1')

t2 = Timer('for i in range(20): x = func2(i)',

... 'from __main__ import func2')

min(t1.repeat(number=10, repeat=5))

7.3219029903411865

min(t2.repeat(number=10, repeat=5))

4.530779838562012

The first function does approximately 60% more work than the first, all
of it unnecessary overhead.





--
http://mail.python.org/mailman/listinfo/python-list


Re: If/then style question

2010-12-18 Thread Francesco

On 17/12/2010 0.51, Steven D'Aprano wrote:

Don't get me wrong... spaghetti code is*bad*. But there are other ways
of writing bad code too, and hanging around inside a function long after
you've finished is also bad:

def function(arg):
 done = False
 do_something()
 if some_condition:
 result = finished
 done = True
 if not done:
 do_something_else()
 if another_condition:
 result = now we're finished
 done = True
 if not done:
 do_yet_more_work()
 if third_condition:
 result = finished this time for sure
 done = True
 if not done:
 for i in range(100):
 if not done:
 do_something_small()
 if yet_another_condition:
 result = finally done!
 done = True
 return result

It's far more complicated than it need be, and does*lots*  of unnecessary
work. This can be written more simply and efficiently as:

def function(arg):
 do_something()
 if some_condition:
 return finished
 do_something_else()
 if another_condition:
 return now we're finished
 do_yet_more_work()
 if third_condition:
 return finished this time for sure
 for i in range(100):
 do_something_small()
 if yet_another_condition:
 return finally done!


I agree to your point, but I'm afraid you chose a wrong example (AFAIK, and 
that's not much).
Sure, the second version of function(arg) is much more readable, but why do you think the first one would do *lots*  of unnecessary 
work?

All the overhead in that function would be:
  if some_condition, three IF tests, and you know that's NOT a lot!
  if no conditions were met, (worst case) the first version would return an exception (unless result was globally defined) while 
the second would happily return None. Apart from this, the overhead in the first one would amount to one million IF tests, again not 
a lot these days. I don't think I would rewrite that function, if I found it written in the first way...

I don't mean that the fist example is better, just I'm sure you could imagine a 
more compelling proof of your concept.
Maybe there's something I don't know... in that case, please enlighten me!

Francesco
--
http://mail.python.org/mailman/listinfo/python-list


Re: Case Sensitive Section names configparser

2010-12-08 Thread Francesco Bochicchio
On 8 Dic, 11:32, RedBaron dheeraj.gup...@gmail.com wrote:
 Is there any way by which configParser's get() function can be made
 case insensitive?

If you don't care about the case of the config parameter values, you
could pre-convert the input to
configParser all in UPPER or lower letter with a file-like object like
this (NOT TESTED):

class AllUpperFile(object):
def __init__(self, fname): self.fp = file(fname)
def readline(self): return self.fp.readline().upper()

and the use configParser.readfp method to feed the file-like object to
the config parser

 myConfigparser.readfp( AllUpperFile(myconnfigfile.cfg)

HTH

Ciao

FB
-- 
http://mail.python.org/mailman/listinfo/python-list


[issue10042] total_ordering stack overflow

2010-10-07 Thread Francesco Ricciardi

New submission from Francesco Ricciardi francesco.riccia...@hp.com:

Tested with version 3.2a2. Not tested on version 2.7.

The current implementation of functools.total_ordering generates a stack 
overflow because it implements the new comparison functions with inline 
operator, which the Python interpreter might reverse if other does not 
implement them. Reversing the comparison makes the interpreter call again the 
lambda function for comparison generating a stack overflow.

Run the attached test file for an example of this behavior.

--
components: Library (Lib)
files: test_total_ordering.py
messages: 118096
nosy: francescor
priority: normal
severity: normal
status: open
title: total_ordering stack overflow
type: crash
versions: Python 3.2
Added file: http://bugs.python.org/file19144/test_total_ordering.py

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue10042
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue10042] total_ordering stack overflow

2010-10-07 Thread Francesco Ricciardi

Francesco Ricciardi francesco.riccia...@hp.com added the comment:

Attached there is a solution of the problem, by implementing each comparison 
only with the class __xx__ and __eq__ operators.

Also in the file there is a complete test suite for it.

--
Added file: http://bugs.python.org/file19145/new_total_ordering.py

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue10042
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Comparing lists

2010-08-16 Thread Francesco Bochicchio
Hi all,

anybody can point me to a description of how the default comparison of
list objects (or other iterables) works?

Apparently l1   l2 is equivalent to  all ( x  y  for  x,y in
zip( l1, l2) ), has is shown in the following tests, but I can't find
it described anywhere:

 [1,2,3]  [1,3,2]
True
 [1,2,3]  [1,2,4]
True
 [1,2,3]  [2,2,3]
True
 [1,2,3]  [0,1,3]
False
 [1,2,3]  [0,2,3]
False
 [1,2,3]  [1,1,3]
False
 [1,2,3]  [1,2,2]
False


Ciao
---
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Weird Python behaviour

2010-08-10 Thread Francesco Bochicchio
On 10 Ago, 13:58, Jonas Nilsson j...@spray.se wrote:
 Hello,

 Lets say that I want to feed an optional list to class constructor:

 class Family():
         def __init__(self, fName, members = []):
                 self.fName = fName
                 self.members = members

 Now, lets add members to two different instances of Family:

 f1 = Family(Smith)
 f1.members.append(Bill)

 f2 = Family(Smithers)
 f2.members.append(Joe)

 Finally, lets look at the members in the Smithers family:

 print f2.members
 output: ['Bill', 'Joe']

 Why on earth is the output ['Bill', 'Joe']!? Is there a simple  
 solution that separates f1 and f2 without forcing me to write code for  
 the special case when you don't feed members to the __init__()-function?

 /Jonas

You stumbled in two python common pitfalls at once :-)
One, the default arguments issue, was already pointed to you.

The other one is that python variables are just names for objects.
Assigning a variable never mean making a copy, it just means using
another name for the same object.
There used to be a very nice (also graphic) explanationor this
somewhere on the web, but my googling skills failed me this time,
so instead I'll show you the concept using your own code:

 class Family:
... def __init__(self, fName, members = []):
... self.fname = fName
... self.members = members
...
 mlist = [Bill]
 f1 = Family(Smiths, mlist )
 mlist.append( John ) # attempt to not-so-clever reyse of the sme variable
 f2 = Family(Smithers, mlist )
 f1.members
['Bill', 'John']

Now my example is a bit contrieved but I'm sure you got the idea : in
your example is better to copy the list with
  self.members = members[:].

Better yet, you could make use of python arguments grouping feature :
 class Family:
... def __init__(self, fName, *members ):
... self.members = list(members) # because members is a
tuple
... self.fname = fName
...
 f1 = Family(Smith)
 f1.members.append(Bill)
 f2 = Family(Smithers)
 f2.members.append(Joe)
 f2.members
['Joe']
 f1.members
['Bill']

This solves your no initial member special case and allows for an
easier syntax for creating class instances
(no brackets involved)

 f3 = Family(Bochicchio, Angelo, Francesco, Mario)
 f3.members
['Angelo', 'Francesco', 'Mario']



Ciao

FB



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Weird Python behaviour

2010-08-10 Thread Francesco Bochicchio
On 10 Ago, 17:57, Stefan Schwarzer sschwar...@sschwarzer.net wrote:
 Hi,

 On 2010-08-10 17:01, Francesco Bochicchio wrote:

  There used to be a very nice (also graphic) explanationor this
  somewhere on the web, but my googling skills failed me this time,
  so instead I'll show you the concept using your own code:

 Probably this isn't the page you're referring to, but I only
 recently gave a beginners' talk at EuroPython:

 http://sschwarzer.com/download/robust_python_programs_europython2010.pdf

 The topic of identity and assignments starts on slide 7,
 nice graphics start on slide 10. ;-)

 Stefan

Also good :-)
But I finally found the page I was referring to:

http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables


Ciao
---
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Minor annoyances with properties

2010-05-27 Thread Francesco Bochicchio
On 27 Mag, 14:37, eb303 eric.brunel.pragma...@gmail.com wrote:
 Hello all,

 I've been using Python properties quite a lot lately and I've found a
 few things that are a bit annoying about them in some cases. I
 wondered if I missed something or if anybody else has this kind of
 problems too, and if there are better solutions than the ones I'm
 using ATM.

 The first annoyance is when I want to specialize a property in a
 subclass. This happens quite often actually, and it is even sometimes
 the reason why a plain attribute is turned into a property: a subclass
 needs to do more things than the superclass when the property is
 updated for example. So, of course, my first try was:

 class A(object):
   def __init__(self):
     self._p = None
   def _get_p(self):
     return self._p
   def _set_p(self, p):
     self._p = p
   p = property(_get_p, _set_p)
 class B(A):
   def _set_p(self, p):
     ## Additional things here…
     super(B, self)._set_p(p)

 And of course, it doesn't work: the property has been bound to
 A._set_p in A, so any new definition of _set_p in any subclass does
 not replace the set method for the property. So I always have to add a
 line:
 p = property(A._get_p, _set_p)
 in the subclass too. This is a bit awkward to me, since I have to
 specify the superclass's name (super(…) can't be used, since it should
 take B as an argument, and B isn't defined yet…). Do I miss something?
 Is this the way to do it, or is there a better one?


Don't know if is better, but you could add a level of indirection to
solve it

 class A(object):
   def __init__(self):
 self._p = None
   def _get_p(self):
 return self._p
   def _set_p(self, p):
 self._p = p
   def _virtual_get_p (self): _get_p(self)
   def _virtual_set_p (self,v): _set_p(self, v)
   p = property(_virtual_get_p, _virtual_set_p)

At this point, the subclasses of A can reimplement _get_p and _set_p
as they like (I think)

Ciao
-
FB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First Tkinter script: requesting comments

2010-05-23 Thread Francesco Bochicchio
On 21 Mag, 23:51, Bart Kastermans bkast...@gmail.com wrote:
 I wrote a first script using Tkinter.  As I am new to its
 use, I am only just feeling my way around.  I would very
 much like comments on the design of the script (and in fact
 any other comments on my code would also be very welcome).

 I have it posted (with syntax coloring) at:

 http://kasterma.wordpress.com/2010/05/21/first-experiments-with-tkinter/

 But will also include it here for convenience.

 Thanks for any help,

 Best,
 Bart

 ***

 #!/usr/bin/env python
 #
 # Getting a list of students and grades displayed so that grades can
 # be updated, and we poll these changes (so that in the future we can
 # act on it).
 #
 # Bart Kastermans,www.bartk.nl

 
 Design of the window

       +-+
       |  root                                                       |
       |  +--+   |
       |  | title_frame                                          |   |
       |  |  +--+                    |   |
       |  |  | Label(title)                 |                    |   |
       |  |  |                              |                    |   |
       |  |  +--+                    |   |
       |  +--+   |
       |  +--+   |
       |  | exam_grades_frames                                   |   |
       |  |  +-+ |   |
       |  |  | Frame(ex)                                       | |   |
       |  |  | ++  +-+ | |   |
       |  |  | | Entry(name)        |  | Entry(grade)        | | |   |
       |  |  | |                    |  |                     | | |   |
       |  |  | ++  +-+ | |   |
       |  |  +-+ |   |
       |  |                                                      |   |
       |  +--+   |
       |                                                             |
       |                 +-+                     |
       |                 | quit_button         |                     |
       |                 |                     |                     |
       |                 +-+                     |
       +-+

 

 from Tkinter import *

 # global info for this specific example

 # four students
 no_stud = 4
 exam_grades = [1,2,3,4]
 names = [Ben, Jim, James, Mel]
 # upper bound for name length
 max_name_len = max (map (len, names))

 # set up root window
 root = Tk()
 root.geometry (400x400)

 exam_grades_string = map (lambda x: StringVar (root,str (x)), exam_grades)

 names_string = map (lambda x: StringVar (root, x), names)

 def setup ():
      setup the window with the list of students.

     This is test-code to figure out what the app finally should look
     like.
     

     # title frame, with title Grade Correction in it
     title_frame = Frame(root)
     title_frame.pack (fill=X)

     w = Label (title_frame, text = Grade Correction, font = (Helvetica, 
 25))
     w.pack (side=LEFT)

     # from to hold the list of grades
     exam_grades_frame = Frame (root)
     exam_grades_frame.pack (fill=BOTH)

     exam_label = Label (exam_grades_frame, text=EXAMS)
     exam_label.pack ()

     # set up the list of grades
     for i in range (0,no_stud):
         # a frame per student
         ex = Frame (exam_grades_frame)
         ex.pack ()
         # name on the left
         name = Entry (ex, textvariable=names_string[i], width=max_name_len+2)
         name.config (state=DISABLED)
         name.pack (side=LEFT)
         # grade next to it
         grade = Entry (ex, textvariable=exam_grades_string [i], width=4)
         grade.pack (side=LEFT)

     # button to quit the application
     qb = Button (root)
     qb ['text'] = quit
     qb ['command'] = root.quit
     qb.pack ()

 def to_int (st):
      helper function to convert strings to integers.

     Empty string represents 0.
     
     if len (st) == 0:
         return 0
     else:
         return int (st)

 def get_curr_grades ():
      extract the grades from exam_grades_string.

     exam_grades_string consists of StringVar that get updated when the
     fields are updated in the GUI.
     
     grades = []
     for i in range (0, no_stud):
         grades.append (exam_grades_string [i].get())
     return grades

 # get the current grades
 curr_grades = map (to_int, get_curr_grades ())

 def poll_exams ():
      function that keeps polling the current grades, looking for changes
     global curr_grades
     new_grades = map (to_int, get_curr_grades ())
     if new_grades != 

Re: solve a newspaper quiz

2010-05-10 Thread Francesco Bochicchio
On 9 Mag, 11:20, superpollo ute...@esempio.net wrote:
 if a b c are digits, solve ab:c=a*c+b

 solved in one minute with no thought:

 for a in range(10):
      for b in range(10):
          for c in range(10):
              try:
                  if (10.*a+b)/c==a*c+b:
                      print %i%i:%i=%i*%i+%i % (a,b,c,a,c,b)
              except:
                  pass

 any suggestion for improvement?

 bye

The obvious one-liner. Maybe not an improvement, but more compact (I
included the solutions for the really lazy ones).
But you need to think just one second to exclude 0 from the values of
c and avoid a divide by zero exception.


 [(a,b,c) for a in range(10) for b in range(10) for c in range(1,10) if 
 (a*10+b)/c == a*c+b ]
[(0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 0, 5), (0, 0, 6), (0,
0, 7), (0, 0, 8), (0, 0, 9), (0, 1, 1), (0, 2, 1), (0, 3, 1), (0, 4,
1), (0, 5, 1), (0, 6, 1), (0, 7, 1), (0, 8, 1), (0, 9, 1), (1, 0, 3),
(1, 5, 2), (1, 6, 2), (2, 0, 3), (2, 1, 3), (3, 1, 3), (4, 1, 3), (4,
2, 3), (5, 2, 3), (6, 2, 3), (6, 3, 3), (7, 3, 3), (8, 3, 3), (8, 4,
3), (9, 4, 3)]


Ciao
---
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fast Efficient way to transfer an object to another list

2010-05-01 Thread Francesco Bochicchio
On 1 Mag, 05:35, Steven D'Aprano st...@remove-this-
cybersource.com.au wrote:


 def transfer_stock(stock_code, old_list, new_list):
      Transfer a stock from one list to another 
     while True:  # loop forever
         try:
             i = old_list.index(stock_code)
         except ValueError:
             # not found, so we're done
             break
         new_list.append(old_list[i])
         del old_list[i]
     return new_list

 --
 Steven

I think this could be slower than doing like the OP, since  'index'
rescan the whole list every time
while doing an explicit loop you only scan the list once.

Anyway i think that list.extract( old_list, predicate ) - new_list
would be a nice addition to the standard library
(possibly a C faster version of what one could implement in
python) ... and since the library is not under moratorium
maybe we will have it ...  the semantic could be like th OP asked:

--- code begins

class ListE(list):
def extract(self, predicate):
res = []
for idx, el in enumerate(self):
if predicate(el):
res.append( self.pop(idx) )
return res

class Stock(object):
def __init__(self, code):
self.code = code
def __repr__(self): return Stock: code=%d % self.code

l = ListE( Stock(n) for n in range(19) )

subl = l.extract( lambda x: x.code in (1,4, 9) )

print  l = , l
print  subl = , subl

--- code ends
--- results

 l =  [Stock: code=0, Stock: code=2, Stock: code=3, Stock: code=5,
Stock: code=6, Stock: code=7, Stock: code=8, Stock: code=10, Stock:
code=11, Stock: code=12, Stock: code=13, Stock: code=14, Stock:
code=15, Stock: code=16, Stock: code=17, Stock: code=18]
subl =  [Stock: code=1, Stock: code=4, Stock: code=9]




Ciao
---
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2010-04-26 Thread Francesco Del Degan

Changes by Francesco Del Degan f.delde...@ngi.it:


Added file: http://bugs.python.org/file17085/timemodule-gmtime-r265.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2010-04-26 Thread Francesco Del Degan

Changes by Francesco Del Degan f.delde...@ngi.it:


Added file: http://bugs.python.org/file17086/timemodule-gmtime-r27b1.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2010-04-26 Thread Francesco Del Degan

Changes by Francesco Del Degan f.delde...@ngi.it:


Added file: http://bugs.python.org/file17087/timemodule-gmtime-r312.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2010-04-26 Thread Francesco Del Degan

Changes by Francesco Del Degan f.delde...@ngi.it:


Added file: http://bugs.python.org/file17088/timemodule-gmtime-3-trunk.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2010-04-26 Thread Francesco Del Degan

Changes by Francesco Del Degan f.delde...@ngi.it:


Removed file: http://bugs.python.org/file16351/timemodule-gmtime-2-trunk.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2010-04-26 Thread Francesco Del Degan

Changes by Francesco Del Degan f.delde...@ngi.it:


Removed file: http://bugs.python.org/file16352/timemodule-gmtime-2-r27a3.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2010-04-26 Thread Francesco Del Degan

Changes by Francesco Del Degan f.delde...@ngi.it:


Removed file: http://bugs.python.org/file16353/timemodule-gmtime-2-r311.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2010-04-26 Thread Francesco Del Degan

Changes by Francesco Del Degan f.delde...@ngi.it:


Removed file: http://bugs.python.org/file16354/timemodule-gmtime-2-r264.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2010-04-26 Thread Francesco Del Degan

Francesco Del Degan f.delde...@ngi.it added the comment:

Fixed typos, new patches added

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2010-04-26 Thread Francesco Del Degan

Francesco Del Degan f.delde...@ngi.it added the comment:

I thinks that isn't a so easy decision to take.

And there are some other issues, imho:

1. timegm function is not specified by any standard (POSIX). The portable way 
(setting TZ, calling mktime, restore TZ) is a pure hack (could not work in 
future multithreaded environments).
2. if we want to strictly follow the time.h definition from POSIX standards, 
the timegm function should be kept away from time module (as now).
3. timegm seems to have some issues on mingw32. 
4. Solaris doesn't come with the timegm function out-of-the-box.

We could give up at this point.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: passing command line arguments to executable

2010-04-04 Thread Francesco Bochicchio
On 3 Apr, 19:20, mcanjo mca...@gmail.com wrote:
 On Apr 3, 11:15 am, Patrick Maupin pmau...@gmail.com wrote:



  On Apr 3, 11:09 am, mcanjo mca...@gmail.com wrote:

   I have an executable (I don't have access to the source code) that
   processes some data. I double click on the icon and a Command prompt
   window pops up. The program asks me for the input file, I hit enter,
   and then it asks me for and output filename, I hit enter a second time
   and it goes off and does its thing and when it is finished running the
   Command Prompt goes away and I have my new output file in the same
   directory as my executable and input file. I would like to be able to
   batch process a group of files. I thought about using os.spawnv() in
   a loop and at each iteration of the loop passing in the file in and
   out names but that didn't work. Does anyone have any ideas?

  You need to look at the subprocess module, and use pipes.

  Regards,
  Pat

 I tried doing the following code:

 from subprocess import Popen
 from subprocess import PIPE, STDOUT
 exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr =
 STDOUT)
 exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0]

 and the Command Prompt opened and closed, no exceptions were generated
 but the program didn't run. Am I doing something wrong?

I would try a couple of things (never done what you are trying to do,
so my suggestions may be useless ):
1. use shell=True as parameter of Popen
2. capture the output of communicate method, which returns whatever
the process emits on standard output and standard error: there could
be some message that give you hints about the solution.

Ciao
--
FB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to access args as a list?

2010-04-04 Thread Francesco Bochicchio
On 4 Apr, 00:58, kj no.em...@please.post wrote:
 Suppose I have a function with the following signature:

 def spam(x, y, z):
     # etc.

 Is there a way to refer, within the function, to all its arguments
 as a single list?  (I.e. I'm looking for Python's equivalent of
 Perl's @_ variable.)

 I'm aware of locals(), but I want to preserve the order in which
 the arguments appear in the signature.

 My immediate aim is to set up a simple class that will allow me to
 iterate over the arguments passed to the constructor (plus let me
 refer to these individual arguments by their names using an
 instance.attribute syntax, as usual).

 The best I have managed looks like this:

 class _Spam(object):
     def __init__(self, x, y, z):
         self.__dict__ = OrderedDict(())
         for p in inspect.getargspec(_Spam.__init__).args[1:]:
             self.__dict__[p] = locals()[p]

     def __iter__(self):
         return iter(self.__dict__.values())

 but rolling out inspect.getargspec for this sort of thing looks to
 me like overkill.  Is there a more basic approach?

 P.S. this is just an example; the function I want to implement has
 more parameters in its signature, with longer, more informative
 names.

Hi, I once tried something to emulate in python the way Scala language
allows to automatically generate class attributes from constructor
parameter. I never tried in real code, but see if it fits your bill.
It uses class decorators though, so only works with python3. Here is
my code:

class FieldsDecorator:
It adds a generic scala-like constructor to a class.
 You can create as instance as c = MyClass(f1=3, f2=4)
 and have automatically c.f1=3, c.f2=4.
 Only parameter names listed in the decorator are allowed.

def __init__(self, *names):
self.names = names

def __call__(self, cls):
def constructor(instance, **kwds):
for n,v in kwds.items():
if n in self.names:
setattr(instance, n, v)
else: raise TypeError(%s is not a valid field % s )
setattr(cls, '__init__', constructor )
return cls


@FieldsDecorator(uno, due)
class Prova:
pass

p = Prova(uno=12, due=9)
print (p.uno, p.due )

Ciao

FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to start a python script only once

2010-03-14 Thread Francesco Bochicchio
On 13 Mar, 19:45, News123 news1...@free.fr wrote:
 Hi,

 I'd like to make sure, that a certain python program will only be run
 once per host. (linux/windows)

 so if the program is started a second time it should just terminate and
 let the other one run.

 This does not have to be the fastest solution, but it should be reliable.

 I have a few ideas, but wonder, which one is the most common

 My ideas so far:

 pid file and file locking
 --
 create a file like program.pid  with the pid of the running program an
 use file locking to avoid race connditions.

 However I currently don't know how to do file locking under windows
 and I don't know how to do file lockng with python and linux.
 I'll start googling.

 sqlite and locking
 
 quite some time ago I used a mysql table and locking as an inter-host mutex.

 Perhaps sqlite would be good enough for an inter process mutex for
 processes on the same host, but I don't know it well enough.

 interprocess mutex
 
 well I even don't know whether something like this exists on linux / windows

 Thanks in advanced for any tips

 N

Apart from file, a portable solution would be to bind to an unused
porta and assume that finding the port busy means that your program is
already running on the port.

On recent python installations there is the multiprocessing module
which provides process-level semaphores, but I don't know how portable
they are.

Ciao

FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing FILE * types using ctypes

2010-03-04 Thread Francesco Bochicchio
On Mar 4, 12:50 am, Zeeshan Quireshi zeeshan.quire...@gmail.com
wrote:
 Hello, I'm using ctypes to wrap a library i wrote. I am trying to pass
 it a FILE *pointer, how do i open a file in Python and convert it to a
 FILE *pointer. Or do i have to call the C library using ctypes first,
 get the pointer and then pass it to my function.

 Also, is there any automated way to convert c struct and enum
 definitions to ctypes data types.

 Zeeshan

Python file objects have a method fileno() whic returns the 'C file
descriptor', i.e. the number used by low level IO in python as well as
in C.
I would use this as interface between python and C and then in the C
function using fdopen to get a FILE * for an already open file for
which you have a file descriptor.

If you don't want change the C interface, you could try using fdopen
in python by loading the standard C library ang using ctypes
to call the function. (I tried briefly but always get 0 from fdopen ).

But if you can change the C code, why not to pass the file name? The
idea of opening the file in python and manage it in C feels a bit
icky ...

Ciao

FB

-- 
http://mail.python.org/mailman/listinfo/python-list


[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2010-02-24 Thread Francesco Del Degan

Francesco Del Degan f.delde...@ngi.it added the comment:

Those are the new updated patches with ifdef wrapped timegm function, docs, and 
a conversion test.

--
Added file: http://bugs.python.org/file16351/timemodule-gmtime-2-trunk.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2010-02-23 Thread Francesco Del Degan

Francesco Del Degan f.delde...@ngi.it added the comment:

I attached a patch that implements timegm according to two constraints:

1. If HAVE_TIMEGM is defined, use it

or

2. If HAVE_MKTIME and HAVE_WORKING_TZSET use a portable way, using mktime 
(taken from timegm(3) man)

Attached patches are for:

r264, r273a1, r311, trunk

What i'm missing just now are the tests (test_time.py) and docs update, if you 
like the patch, i can continue on that.

--
Added file: http://bugs.python.org/file16334/timemodule-gmtime-r264.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue7690] Wrong PEP number in importlib module manual page

2010-01-13 Thread Francesco Ricciardi

New submission from Francesco Ricciardi francesco.riccia...@hp.com:

At the end of section 2.9.1 of the Library Reference, i.e. the introduction to 
the importlib module manual page, there is the See Also box that often we can 
find in the manual pages. The last PEP of the box has the title (Using UTF-8 
as the Default Source Encoding) and number 3128. Number and title collide.

I believe the title is correct, i.e. the numbe should be changed to 3120, and 
the link correspondingly.

--
assignee: georg.brandl
components: Documentation
messages: 97707
nosy: francescor, georg.brandl
severity: normal
status: open
title: Wrong PEP number in importlib module manual page
versions: Python 3.1

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue7690
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue7683] Wrong link in HTML documentation

2010-01-12 Thread Francesco Ricciardi

New submission from Francesco Ricciardi francesco.riccia...@hp.com:

The first page of the Python Tutorial in version 3.1 
(http://docs.python.org/3.1/tutorial/index.html) has the previous topic link 
pointing to What’s New in Python 2.0 instead of What’s New in Python 3.1.

--
assignee: georg.brandl
components: Documentation
messages: 97635
nosy: francescor, georg.brandl
severity: normal
status: open
title: Wrong link in HTML documentation
versions: Python 3.1

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue7683
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue7683] Wrong link in HTML documentation

2010-01-12 Thread Francesco Ricciardi

Francesco Ricciardi francesco.riccia...@hp.com added the comment:

As written in the description, it should point to the What's New in Python 
3.1 page, shouldn't it?

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue7683
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Need help to pass self.count to other classes.

2010-01-06 Thread Francesco Bochicchio
On 6 Gen, 11:11, Bill bsag...@gmail.com wrote:
 After a year with Python 2.5 on my Windows box, I still have trouble
 understanding classes.

 Below, see the batch file and the configuration script for
 my Python interactive prompt.

 The widths of the secondary prompts increase when  the self.count of
 SysPrompt1 exceeds 99.

 I am using a global variable zxc to share self.count, which is not
 Pythonic.

 How can I pass in self.count without a global?
 I did RTFM, aka Google, but to no avail.

 echo py.bat
 set PYTHONSTARTUP=c:\scripts\startup.py
 python
 ^Z

 # startup.py
 # inspired by:
 #http://www.doughellmann.com/PyMOTW/sys/interpreter.html

 import sys

 class SysPrompt1(object):
     def __init__(self):
         self.count = 0
     def __str__(self):
         self.count += 1
         global zxc
         zxc = self.count
         return '[%2d] ' % self.count

 class SysPrompt2(object):
     def __str__(self):
         global zxc
         if zxc  99: return '.. '
         else: return '. '

 class DisplayHook(object):
     def __call__(self, value):
         if value is None: return
         global zxc
         if zxc  99: print '[ out]', value, '\n'
         else: print '[out]', value, '\n'

 class ExceptHook(object):
     def __call__(self, type, value, trace):
         global zxc
         if zxc  99: print '[ err]', value, '\n'
         else: print '[err]', value, '\n'

 sys.ps1 = SysPrompt1()
 sys.ps2 = SysPrompt2()
 sys.displayhook = DisplayHook()
 sys.excepthook = ExceptHook()

First of all, you shouldn't do OOP if you don't feel it. Python,
unlike Java and like C++, supports also procedural programming, so you
can write your scripts without writing classes (but still using
objects, since all in python is an object).
If you have classes with no data and a single __call_ method, then
they are no classes, they are functions (or methods) in disguise.
So, one solution could be to use plain functions and use global as you
already do. 'global' is pythonic if you are not doing OOP, although I
don't like it.

If you want to stick to OOP, then I suggest to have a make
display_hook and except_hook methods of your class SysPrompt1; This
way all your code can access to self.count without needing globals.
As for  your class SysPrompt2,  I don't understand enough your code to
know what you are trying to do. maybe make it a sunclass of
SysPrompt1 ?

HTH

Ciao

FB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting name of passed reference

2009-12-29 Thread Francesco Bochicchio
On 29 Dic, 00:54, Joel Davis callmeclaud...@gmail.com wrote:
 I'm just curious if anyone knows of a way to get the variable name of
 a reference passed to the function.

 Put another way, in the example:

   def MyFunc ( varPassed ):
      print varPassed;

   MyFunc(nwVar)

 how would I get the string nwVar from inside of MyFunc? is it
 possible?


The following code shows one way to get both function name and
argument names from inside a function using module inspect in python
2.6:

import inspect

def myfunc(arg1, arg2):
f = inspect.currentframe()
funcname = inspect.getframeinfo(f).function
numargs =  f.f_code.co_argcount
argnames = f.f_code.co_varnames[:numargs]
print funcname, argnames

myfunc(1, ppp)

NOTE: it does not list parameters passed as list (*args) or as dict
(**kwd).

P.S . I use this to generate automatically trace messages of type
called myfunc( arg1=1, arg2=ppp ).
But I currently lack  a way, from inside a method, to determine the
name of the class to which the
method belong, so I could automatically generate trace messages of
type class.method called etc 
Pointers are welcome.

Ciao
-
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to iterate the input over a particular size?

2009-12-28 Thread Francesco Bochicchio
On 27 Dic, 22:29, joy99 subhakolkata1...@gmail.com wrote:
 On Dec 27, 8:42 pm, Benjamin Kaplan benjamin.kap...@case.edu wrote:



  On Sun, Dec 27, 2009 at 9:44 AM, joy99 subhakolkata1...@gmail.com wrote:
   Dear Group,

   I am encountering a small question.

   Suppose, I write the following code,

   input_string=raw_input(PRINT A STRING:)
   string_to_word=input_string.split()
   len_word_list=len(string_to_word)
   if len_word_list9:
               rest_words=string_to_word[9:]
               len_rest_word=len(rest_words)
               if len_rest_word9:
                        remaining_words=rest_words[9:]

   In this program, I am trying to extract first 9 words from an
   indefinitely long string, until it reaches 0.
   Am I writing it ok, or should I use while, or lambda?
   If any one can suggest.

   Hope you are enjoying a nice vacation of Merry Christmas. If any one
   is bit free and may guide me up bit.

   Wishing you a happy day ahead,
   Best Regards,
   Subhabrata.
   --

  You want the first 9 words? string_to_word[:9]
  You want the last 9 words? string_to_word[-9:]

  If you want the groups of words, use a loop- that's the only way to
  get all of them for any length list.

  http://mail.python.org/mailman/listinfo/python-list-Hide quoted text -

  - Show quoted text -- Hide quoted text -

  - Show quoted text -

 Dear Group,
 Answers were good. But I am looking for a smarter solution like:

 for i[:2] in list:
 

 etc. or by doing some looping over loop.
 Do not worry I'll work out the answer.

 Wishing you a happy day ahead,
 Regards,
 Subhabrata.

Not sure I understood your question, but if you need just to plit a
big list in sublists of no more than 9 elements, then you can do
someting like:

def sublists(biglist, n ):
Splits a big list in sublists of max n elements
prev_idx = 0; res = []
for idx in xrange(n, len(biglist)+n, n ):
res.append( biglist[prev_idx:idx] )
prev_idx = idx
return res

I would not be surprised if somewhere in python standard library there
is something like this (possibly better), but
could not find anything.

Another solution could be this smarter-looking but less readeable one
liner:

sublists = [ big_list[i:(i+9)] for i in xrange( 0, len
(big_list)+9, 9) if i  len(big_list) ]


P.S : if your biglist is huge (but being typed in I don't think so)
then you better convert the sublists function in a
generator.


HTH

Ciao

FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (help)Tkinter, how to make labels scrolling?

2009-12-28 Thread Francesco Bochicchio
On 28 Dic, 09:44, Ren Wenshan renws1...@gmail.com wrote:
 Hi, everyone:

    I am new to programming and Python and these days I've been working
 on a
 tiny program for practice and encountered with a problem.

    My tiny program read a line from a data file one time, and store it
 in a list, till the list is full. This is the init.
    Then when I press Button Start, I want the program will read a
 line,
 list.pop(0) list.append(line) in a loop. Thus, make the labels
 scrolling.
    English is not my mother tongue, I hope I've made myself
 understood.

    the whole source code:

 from Tkinter import *
 import sys
 import time

 # position of buttons
 row_button = 5
 col_button = 4

 # font size
 size_title = 20
 size_button = 12
 size_text = 14

 # the length of name_list
 Len_List = 3

 class meal( Frame ):

     def __init__(self):
         Frame.__init__(self)
         self.pack( expand = YES, fill = BOTH)
         self.master.title(Languages)

         self.label_1 = Label(self, text = Too many languages to
 choose..., font = (arial, size_title))
         self.label_2 = Label(self, text = Which is the Lucky one,
 font = (arial, size_title-4))
         self.label_1.grid(row = 0, column = 0)
         self.label_2.grid(row = 1, column = 2)

         self.button_start = Button(self, text = start, font =
 (arial, size_button), command = self.start)
         self.button_stop = Button(self, text = stop, font =
 (arial, size_button))
         self.button_quit = Button(self, text = quit, font =
 (arial, size_button), command = self.quit)

         self.button_start.grid(row = row_button, column = col_button)
         self.button_stop.grid(row = row_button, column = col_button+1)
         self.button_quit.grid(row = row_button,column = col_button+2)

         self.name_list = [None] * Len_List
         self.label_list = [None] * Len_List

         self.fp = open(data.txt, 'r')
         for i in range(Len_List):
             self.name_list[i] = self.fp.readline()
         for i in range(Len_List):
             self.label_list[i] = Label(self, text = self.name_list[i],
 font = (arial, 12))
             self.label_list[i].grid(row = 2+i, column = 2)

     def start(self):
         self.line = self.fp.readline()
         if not self.line:
             self.fp.seek(0)
             self.line = self.fp.readline()
         self.name_list.pop(0)
         self.name_list.append(self.line)

         for i in range(Len_List):
             self.label_list[i].destroy()
             self.label_list[i] = Label(self, text = self.name_list[i],
 font = (arial, 12))
             self.label_list[i].grid(row = 2+i, column = 2)

     def quit(self):
         sys.exit(0)

 app = meal()
 app.mainloop()

 Best wishes

 Vincent Ren

Hi,

if you want to realize an 'animated scrolling' effect, you need to
move the scrolling code out of the start callback
in a function which is called periodically by the GUI mainloop. In
Tkinter, you can do that using Toplevel.after to
have a fuction be called after a timeout. Here is your 'meal' class
with the modifications needed to make an
'animated scroll'. I renamed your start method as _scroll_text and
wrote  new start and stop methods to start and stop
the scrolling.

Ciao
-
FB


lass meal( Frame ):
SCROLL_DELAY = 500 # milliseconds
def __init__(self):
Frame.__init__(self)
self.pack( expand = YES, fill = BOTH)
self.master.title(Languages)

self.label_1 = Label(self, text = Too many languages to
choose..., font = (arial, size_title))
self.label_2 = Label(self, text = Which is the Lucky one,
font = (arial, size_title-4))
self.label_1.grid(row = 0, column = 0)
self.label_2.grid(row = 1, column = 2)

self.button_start = Button(self, text = start, font =
(arial, size_button), command = self.start)
self.button_stop = Button(self, text = stop, font =
(arial, size_button), command = self.stop )
self.button_quit = Button(self, text = quit, font =
(arial, size_button), command = self.quit)

self.button_start.grid(row = row_button, column = col_button)
self.button_stop.grid(row = row_button, column = col_button+1)
self.button_quit.grid(row = row_button,column = col_button+2)

self.name_list = [None] * Len_List
self.label_list = [None] * Len_List

self.fp = open(data.txt, 'r')
for i in range(Len_List):
self.name_list[i] = self.fp.readline()
for i in range(Len_List):
self.label_list[i] = Label(self, text = self.name_list[i],
font = (arial, 12))
self.label_list[i].grid(row = 2+i, column = 2)

self.after_id = None

def _scroll_text(self):
#print _scroll_text
self.line = self.fp.readline()
if not self.line:
self.fp.seek(0)
self.line = self.fp.readline()
self.name_list.pop(0)
self.name_list.append(self.line)

for i in range(Len_List):
  

Re: iterators and views of lists

2009-12-16 Thread Francesco Bochicchio
On Dec 16, 1:58 pm, Anh Hai Trinh anh.hai.tr...@gmail.com wrote:


 You might be interested in this library http://pypi.python.org/pypi/
 stream.

 You can easily create arbitrary slice, for example

   i = mylist  takei(primes())

 will return an iterator over the items of mylist with a prime number
 index, given that primes() return an iterator over prime numbers.



Nice :-)

I was starting to experiment data flow programming with python myself,
although I'm just playing with it..
I find the idea of data flow programming fascinatin, and wonder if it
can be considered a general-purpose program paradigm.

Ciao
-
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


delete column content

2009-11-29 Thread Francesco Pietra
Hi:
How to replace with blank the single-character in column 21 of a pdb
file (in pdb numbering it is column 22). Attached is an incomplete
exercise with slices. I am unable to get real plain text with gmail.

Thanks for help

francesco pietra
# Sample line
# Slice indexes cut to the left of the corrresponding item index
#   1 2 3 4 5 6
# 012345678901234567890123456789012345678901234567890123456789012345 ...
# ATOM  1  N   LEU A   1 153.242  64.673  95.851  0.00  0.00   N


data = open('in.pdb', 'r')
outp = open('out.pdb', 'w')

for L in data:
   if L[21] == 'A':
 L = L[ ???
   outp.write(L)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can self crush itself?

2009-11-26 Thread Francesco Guerrieri
On Thu, Nov 26, 2009 at 8:04 AM, Gregory Ewing
greg.ew...@canterbury.ac.nzwrote:

 n00m wrote:

  I can't understand why we can get __name__, but not __dict__,
 on the module level?


 For much the same reason that you can see your own
 feet but (unless you look in a mirror) you can't
 see your own eyes.



+1 QOTW

Francesco
-- 
http://mail.python.org/mailman/listinfo/python-list


reposition a column

2009-11-25 Thread Francesco Pietra
Hi:

In a pdb file made of lines ATOM .. (see attachment as I was unable
to obtain plain text with gmail) I would like to reposition the second
W from column 19 to 17 ( (Python numbering; in pdb numbering it
would be 20 18). I started with bold slices, then I was unable to
complete the script. Much obliged for help.

francesco pietra
# Sample line
# Slice indexes cut to the left of the corrresponding item index
#   1 2 3 4 5 6
# 012345678901234567890123456789012345678901234567890123456789012345 ...
# ATOM  1  W W 1   0.690  35.960  33.300  1.00  0.00

data = open('out.2.5.2.5.2.0.pdb', 'r')
outp = open('rect.out.2.5.2.5.2.0.pdb', 'w')

for L in data:
   if L[19] == 'W':
 L = 
   outp.write(L)
-- 
http://mail.python.org/mailman/listinfo/python-list


[issue755660] allow HTMLParser to continue after a parse error

2009-11-10 Thread Francesco Frassinelli

Francesco Frassinelli frap...@gmail.com added the comment:

Site: http://ftp.vim.org/pub/vim/unstable/patches/

Outuput without error customized function:
[...]
  File ./takeit.py, line 54, in inspect
parser.feed(data.read().decode())
  File /home/frafra/Scrivania/takeit/html/parser.py, line 107, in feed
self.goahead(0)
  File /home/frafra/Scrivania/takeit/html/parser.py, line 163, in goahead
k = self.parse_declaration(i)
  File /usr/local/lib/python3.1/_markupbase.py, line 97, in
parse_declaration
decltype, j = self._scan_name(j, i)
  File /usr/local/lib/python3.1/_markupbase.py, line 387, in _scan_name
% rawdata[declstartpos:declstartpos+20])
  File /home/frafra/Scrivania/takeit/html/parser.py, line 122, in error
raise HTMLParseError(message, self.getpos())
html.parser.HTMLParseError: expected name token at '! gives an error
me', at line 153, column 48

Output with error customized function:
[...]
  File ./takeit.py, line 55, in inspect
parser.feed(data.read().decode())
  File /home/frafra/Scrivania/takeit/html/parser.py, line 107, in feed
self.goahead(0)
  File /home/frafra/Scrivania/takeit/html/parser.py, line 163, in goahead
k = self.parse_declaration(i)
  File /usr/local/lib/python3.1/_markupbase.py, line 97, in
parse_declaration
decltype, j = self._scan_name(j, i)
TypeError: 'NoneType' object is not iterable

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue755660
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue755660] allow HTMLParser to continue after a parse error

2009-11-10 Thread Francesco Frassinelli

Francesco Frassinelli frap...@gmail.com added the comment:

I'm using Python 3.1.1 and the patch (patch.txt, provided by smroid)
works very well. It's usefull, and I really need it, thanks :)
Without this patch, I can't parse: http://ftp.vim.org/pub/vim/ (due to a
fake tag, like u...@mail.com), and many others websites.

I hope this patch will be merged in Python 3.2 :)

--
nosy: +frafra

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue755660
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Looking for help getting tkinter to work.

2009-11-01 Thread Francesco Bochicchio
On Nov 1, 4:06 am, Shue Boks shoebox56car...@gmail.com wrote:
 I tried to compile Python and Tcl/Tk on Linux using the following
 files:

 Python-3.1.1.tar.gz
 tcl8.5.7-src.tar.gz

 Cannot get tkinter to work after compiling  installing Tcl/Tk.  I get
 the following error after compiling Python:

 Python build finished, but the necessary bits to build these modules
 were not found:
 _tkinter
 To find the necessary bits, look in setup.py in detect_modules() for
 the module's name.

 Are the above files the correct versions to get tkinter to work?

 Thanks.

The version should be ok. I just compiled python3.1 against tcl/tk
8.5, only I used
the tcl/tk development packages coming with my distribution (Ubuntu).
I used
./configure --with-tk, so if you did not, try that first.

Did you run 'make install' during tcl/tk installation _before_ doing ./
configure in python source
directory?

If so, look where the library files ( e.g. libtk8.5.so ) and include
files (e.g tk.h ) have been placed
and check against the places where the function 'detect_tkinter' in
'setup.py' looks for them.

Ciao
-
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hello, world?

2009-10-28 Thread Francesco Bochicchio
On 28 Ott, 10:40, Gilles Ganault nos...@nospam.com wrote:
 Hello

 I'm reading O'Reily's Python Programming on Win32, but couldn't find
 a simple example on how to create a window with just a label and
 pushbutton.


This is probably because maybe the book addresses how to use python to
do windows-specific
stuff (like using a COM interface) and presumes a basic knowledge of
python in the reader
(just guessing, never read the book )


 If someone has such a basic example handy, I'm interested.

 Thank you.


There are as many way to do it as many GUI toolkits for python you can
find (and there are
many) although they all share a similar structure. Here is the one for
Tkinter, which is the
default python GUI toolkit. The example is copied verbatim from
the python on-line documentation ( section Graphical User Interfaces
with Tk of  The Python Standard Library).



Ciao
--
FB

from Tkinter import *

class Application(Frame):
def say_hi(self):
print hi there, everyone!

def createWidgets(self):
self.QUIT = Button(self)
self.QUIT[text] = QUIT
self.QUIT[fg]   = red
self.QUIT[command] =  self.quit

self.QUIT.pack({side: left})

self.hi_there = Button(self)
self.hi_there[text] = Hello,
self.hi_there[command] = self.say_hi

self.hi_there.pack({side: left})

def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()

root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-28 Thread Francesco Bochicchio

 Just to fuel the flame war, consider a million line Python system. It's not
 uncommon with C++. :-)


In python, with one-miliion lines of code, you can demonstrate
the existence of God, and then demostrate its non-existance by
changing a single line of code  :-)


Ciao
-
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cpython optimization

2009-10-21 Thread Francesco Bochicchio
Il Wed, 21 Oct 2009 10:28:55 -0700, Qrees ha scritto:

 Hello
 
 As my Master's dissertation I chose Cpython optimization. That's why i'd
 like to ask what are your suggestions what can be optimized. Well, I
 know that quite a lot. I've downloaded the source code (I plan to work
 on Cpython 2.6 and I've downloaded 2.6.3 release). By looking at the
 code I've found comment's like this can be optimized by... etc. but
 maybe you guide me what should I concentrate on in my work?
 
 I've 6-7 month  for this and If I create something decent I can publish
 it.
 
 Thank you in advance for any help

If you don't know yet, you could find interesting this project:

   http://code.google.com/p/unladen-swallow/

They too are trying to improve CPython speed.

If you are thinking of language variations  that trade some flexiblity 
for speed, you might be interested in Cython:

http://www.cython.org/

As a simple and plain python user, I would value a version of cython that 
can be used to built faster executables out of almost-python code (that 
is python code with a few additional restructions). Maybe using typing 
inference to avoid declaring explicitely the variable types.

Another interesting place to go is pypy : http://codespeak.net/pypy/dist/
pypy/doc/ . They too have developed a restriced version of python 
(RPython, I think) which should be faster than CPython. They don't work 
with CPython code base, but could give you ideas on what are the 
bottlenecks of python as a language.

Ciao
-
FB


 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clear interface for mail class

2009-10-14 Thread Francesco Bochicchio
On Oct 14, 2:39 pm, Benedict Verheyen benedict.verhe...@gmail.com
wrote:
 Hi,

 I'm trying to come up with a decent interface for my email class.
 Basically, i have one email function but it has many (too many?) variables:

     send_mail(self, send_from, send_to, send_cc, subject, text, 
 separate_emails = False, files=[], inline_files=[], server=localhost,
 charset=iso-8859-1)

 I'm thinking on how i could simplify it and make it look nicer and more easy 
 to use.
 I can reduce the number of arguments by adding functions for the less common 
 tasks
 like adding attachement, inline files and so on.
 Then i would end up with functions like this:

 def __init__(self):
     
     
     self._files=[]
     self._inline_files=[]
 ...

 def add_files(self, files=[]):
     assert type(files)==list
     self._files=files
 ...

 When sending an email, i could check if files where specified and if so, send 
 them too.

 But it doesn't feel right to just have a bunch of small functions to set 
 variables.
 Calling the function would change from:
  (where m is the mail class)
  m.send_mail( from...@work,
               t...@work,
               [],
               Test emailmodule ,
               MSG,
               separate_emails = True,
               files=[attached_pic.png],
               inline_files=[inline_pic.png],
               server=mysmtpserver)

 to:

 m.add_files([attached_pic.png])
 m.add_inline_files([inline_pic.png])
 m.smtp_server(mysmtpserver)
 m.send_mail( from...@work,
              t...@work,
              [],
              Test emailmodule ,
              MSG)

 It looks already better and i could set the smtp server as a class variable,
 but i'm not sure this will present me with the most natural interface to use.

 Or should i make 1 general function that sets vars according to a type?
 For instance: add_header(To,[list_of_recipients])

 This kind of problems seems to happen sometimes: i need to fix something 
 quickly,
 build a script for it, and then i realise that the code i've written is not 
 the best in
 terms of reusability and has some not so great functions or classes.
 Speedy development eh.

 Any ideas are welcome.

 Thanks,
 Benedict

I would add a server class, maybe subclassing something in standard
library, and add to it the 'send' method, so that sending a mail would
be
something like:

myserver = MyMailServer(mysmtpserver, localhost, ) # this only
needs to be done once, not for each mail

m = MyMail( subject, text, separate_emails = False, files=[],
inline_files=[] ) # mail creation

myserver.send( m, from= from...@work, # mail sending
   to = t...@work,
   cc_to= None  )

Note that I put sender and destination senders in the send method, not
as attributes  of the mail object. It makes more sense to me, and yopu
can reuse
the same object if you want to send the same mail to many addresses
( and/or via different servers ).

IN general, un case like yours I use a lot default parameters, as you
did already. Having separate methods to setting specific part of an
object only makes
sens (to me) if you need  first to create an object and later change
some of the attributes. Also, if you are just going to change the
attributes, you do not
need a method: just use the object.attribute = value syntax. If you
are going to need later to do more complex thing, you can always
transform your
attribute in a property.




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Opinions, please, on PEP 8 and local, 3rd party imports

2009-10-03 Thread Francesco Bochicchio
On Oct 2, 9:50 pm, Philip Semanchuk phi...@semanchuk.com wrote:
 Hi all,

 PEP 8 http://www.python.org/dev/peps/pep-0008/ says the following:

     Imports should be grouped in the following order:
     1. standard library imports
     2. related third party imports
     3. local application/library specific imports

 I'm not sure in which category to place local, 3rd-party modules like  
 configobj.


...

 Clearly, the best choice is category 2.5?


Actually 2.5 is doable :-)
I translate it as just after any of 2 and before any of 3

Ciao

FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Want to call a method only once for unittest.TestCase--but not sure how?

2009-09-28 Thread Francesco Bochicchio
On Sep 28, 12:45 pm, Oltmans rolf.oltm...@gmail.com wrote:
 Hello fellow python hackers,

 I'm not an expert when it comes to Python and I'm totally stuck in a
 situation. All of our unit tests are written using built-in 'unittest'
 module. We've a requirement where we want to run a method only once
 for our unit tests. Some background: all of our tests are sub-classes
 of unittest.TestCase module just like following (copy pasting from
 idle)

 class Calculator(unittest.TestCase):

     def setUp(self): pass
     def tearDown(self): pass

     def test_add(self):

         print 'adder'
         print '---'

     def test_multiply(self):
         print 'multiplier'
         print '---'

     def test_divide(self):
         print '==='
         print 'Divide test'
         print '==='

 Our requirement is that for every unit test class we want to run a
 method only once. Method setUp() won't help because it will be called
 before every test method. I've tried using the following

 def __init__(self):
         unittest.TestCase.__init__(self)

 but it throws the following error

 E:\PyPy\Practicepython runner.py

 Traceback (most recent call last):
     suite  = unittest.defaultTestLoader.loadTestsFromNames
 (['Tests.Calculator.Te
 stCase'])
   File C:\Python25\lib\unittest.py, line 565, in loadTestsFromNames
     suites = [self.loadTestsFromName(name, module) for name in names]
   File C:\Python25\lib\unittest.py, line 547, in loadTestsFromName
     return self.loadTestsFromTestCase(obj)
   File C:\Python25\lib\unittest.py, line 507, in
 loadTestsFromTestCase
     return self.suiteClass(map(testCaseClass, testCaseNames))
 TypeError: __init__() takes exactly 1 argument (2 given)

 So I'm completely stumped as to how to create a method that will only
 be called only once for Calculator class. Can you please suggest any
 ideas? Any help will be highly appreciated. Thanks in advance.

The constructor of unittest.TestCase takes an optional test name as
argument, and in the failing code it is called with such an argument,
so when you are subclassing you have to keep the same interface:

 class Calculator(unittest.TestCase):
def __init__(self, name='runTest') :
 unittest.TestCase.__init__(self, name)
 # your staff here

Note that __init__ gets called one time for test *instance*, not one
time for test class. If you want the latest, you could define
classmethods that you call
explicitely at the beginning of your test code:

  class Calculator(unittets.TestCase):
  @classmethod
  def initialize(cls, ...):
  # your staff here

  def test(...): # or wherever your test code starts  code
  Calculator.initialize()
  # other test class initializations
  # run your tests

HTH

Ciao
--
FB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UnboundLocalError - code is short simple

2009-09-28 Thread Francesco Bochicchio
On Sep 28, 6:07 am, pylearner for_pyt...@yahoo.com wrote:
 System Specs:

 Python version = 2.6.1
 IDLE
 Computer = Win-XP, SP2 (current with all windows updates)

 ---­-

 Greetings:

 I have written code for two things:  1) simulate a coin toss, and 2)
 assign the toss result to a winner.  Code for the simulated coin toss
 is in a file named coin_toss.py.  Code for the assignment of the
 toss result is in a file named toss_winner.py.  Each file has one
 simple function:  1) coin_toss(), and 2) toss_winner(), respectively.
 (The code for each file is listed below.)

 Problem:

 I am getting an error when I run toss_winner.py.

 Error Message:

 Traceback (most recent call last):
   File pyshell#2, line 1, in module
     toss_winner()
   File C:/Python26/toss_winner.py, line 7, in toss_winner
     coin_toss = coin_toss()
 UnboundLocalError: local variable 'coin_toss' referenced before
 assignment

 Question #1:

 After reviewing the code below, does anybody know why I am getting
 this error?

 Explanation:

 As I understand, the first statement of the toss_winner() function
 body -- i.e. coin_toss = coin_toss() -- causes four things to
 happen: 1) the coin_toss() function is called, 2) the coin_toss()
 function is executed, 3) the coin_toss() function returns the value of
 its local coin_toss variable, and 4) the returned value of the coin
 toss variable that is local to the coin_toss() function is assigned
 to the coin toss variable that is local to the toss_winner()
 function.

 Given this understanding, it seems I should NOT be getting a
 referenced before assignment error, involving the coin_toss local
 variable of toss_winner().

 Note:

 I am new to programming and Python.  I'm currently self-studying
 Python Programming: An Intro to Computer Science by Zelle.

 Thanks!

 ---

 # toss_winner.py

 from coin_toss import coin_toss

 def toss_winner():

     coin_toss = coin_toss()

     if coin_toss == Heads:
         toss_winner = Player A
         print 'From toss_winner function ',
         print Toss Winner =  + str(toss_winner)

     else:
         toss_winner = Player B
         print 'From toss_winner function ',
         print Toss Winner =  + str(toss_winner)

     return toss_winner

 ---

 # coin_toss.py

 from random import random

 def coin_toss():

     random_number = random()

     if random_number  .5:

         coin_toss = Heads

         print 'From coin_toss function ',
         print Toss result =  + str(coin_toss)

     else:

         coin_toss = Tails

         print 'From coin_toss function ',
         print Toss result =  + str(coin_toss)

     return coin_toss

You should not use the same name (e.g. coin_toss ) for the function
and the variable. Change one of the two, and things will go better.

Ciao
--
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


tool per conversione e trasformazione dati

2009-09-23 Thread Francesco Stablum
Salve,

lavoro in una ditta dove effettuiamo intensamente conversioni di
database, trasformazione dei dati e raccolta da sorgenti diverse,
successive query per fare dei fix eccetera... insomma, un lavoro
bello complesso.
Mi domandavo, insieme ai miei colleghi, se esistono dei tool/framework
per effetturare operazioni di questo tipo e, allargando il discorso al
di la di python, se esiste una disciplina teorica da dove possiamo
attingere informazioni per riorganizzare i nostri programmi e script.

ringrazio per l'attenzione,
Francesco Stablum

-- 
The generation of random numbers is too important to be left to chance
- Robert R. Coveyou
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tool per conversione e trasformazione dati

2009-09-23 Thread Francesco Stablum
I am sorry, the previous mail was intended to be published to the
italian python mailing list, but... whoops, autocomplete tricked me...
I will translate it in English:

Hello,

I work in a company where we do intensively database conversions, data
transformations from different sources, queries of fixes... a very
complex job.
I was wondering if there are any tool/frameworks to do such operations
and if there exist a theoretical scientific branch where we can get
some more informations to reorganize our scripts and programs.

thanks for the attention,
Francesco Stablum

2009/9/23 Francesco Stablum stab...@gmail.com:
 Salve,

 lavoro in una ditta dove effettuiamo intensamente conversioni di
 database, trasformazione dei dati e raccolta da sorgenti diverse,
 successive query per fare dei fix eccetera... insomma, un lavoro
 bello complesso.
 Mi domandavo, insieme ai miei colleghi, se esistono dei tool/framework
 per effetturare operazioni di questo tipo e, allargando il discorso al
 di la di python, se esiste una disciplina teorica da dove possiamo
 attingere informazioni per riorganizzare i nostri programmi e script.

 ringrazio per l'attenzione,
 Francesco Stablum

 --
 The generation of random numbers is too important to be left to chance
 - Robert R. Coveyou




-- 
The generation of random numbers is too important to be left to chance
- Robert R. Coveyou
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: VTK install

2009-09-15 Thread Francesco Bochicchio
On Sep 15, 6:29 am, Gib gib.bo...@gmail.com wrote:
 As part of the MayaVi install, I need to install VTK.  

...

 Since VTK appears to be installed, I'm guessing that either the path
 setting is wrong, or python is not using PYTHONPATH.  How can I check
 that PYTHONPATH is being used?

The paths in PYTHONPATH should show un sys.path python variable. So
just do from a
python prompt import sys; sys.path and check if the VTK directories
are listed.

You colòud aslo tentatively append your path to sys.path and then try
again import vtk
to see if it is a path problem or something else ...

Ciao

FB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The future of Python immutability

2009-09-04 Thread Francesco Bochicchio
On Sep 3, 9:07 pm, Nigel Rantor wig...@wiggly.org wrote:

 Right, this is where I would love to have had more experience with Haksell.

 Yes, as soon as you get to a situation where no thread can access shared
 state that is mutable your problems go away, you're also getting no work
 done becasue the threads, whilst they may be performing lots of
 interesting calculations have no way of allowing the rest of the
 program, or operating system, know about it.


Threads could communicate only with channels, message queue, or
equivalent. Is what
I do that as much as I can, to avoid the headache of sharing data
between threads. It is
less efficient than the shared data model and adds latency, but ensure
that each thread
is self-contained, making for safer programming and opening the way to
better parallelization.
AFAIK erlang Processes  and scala Actors implement a similar model at
language level.

In python, there is kamaelia that implements a similar paradigm,
although it is more concerned
with logical parallelization than with multitheading performance
issue.

I believe this kind of paradigms will bring us to the massive
multicore world easier than FP.
Consider that most FP languages have accepted a compromise and become
'unpure' (i.e. have
constructs to change variable in place). Even haskell, the only pure
FP
language I know (sort of), has things like mutable arrays.
All these features expose current FP languages at the same 'shared
resource' risks of imperative one,
although admittedly at a less level. And FP languages have their own
crop of problems - e.g how to deal
efficiently with deep recursion levels, parameters passed by copy,
huge list built in memory (if you use eager evaluation)
or build-up of thunks (if you use lazy evaluation).

But then, I'm just a programmer, so I could be easily wrong :-)

Ciao
-
FB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: list comprehension troubles..

2009-08-24 Thread Francesco Bochicchio
On 24 Ago, 01:27, mm matta...@gmail.com wrote:
 Hi, I'm trying to replace this...

         # this works but there must be a more pythonic way, right?
         tlist = []
         for obj in self.objs:
             t = obj.intersect(ray)
             if (t != None):
                 tlist.append((obj,t))

 with a list comprehension- can it be done?

 What I need to do is iterate over a list of graphics primitives and
 call their intersect method. If the returned t value is not None then
 I want to store the obj refernence and its t value in a list of tuples
 for further processing. I've tried stuff like ...

         tlist = [(obj,t) for obj,t in (self.objs, obj.intersect(ray))
 if (t != None)]
         tlist = [(obj,t) for obj in self.objs for t in obj.intersect
 (ray) ]
         print  ,len(tlist), tlist

 but they don't work. Any help greatly appreciated. matt

What about this:

def intersections(objlist, ray):
 for obj in objlist: yield obj, obj.intersect(ray)
tlist = [(obj, t) in intersections(self.objs, ray) if t != None ]

It is still quite readable but a bit more compact. More efficient?
Maybe.

Ciao

FB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: your favorite debugging tool?

2009-08-23 Thread Francesco Bochicchio
On Aug 22, 4:25 pm, Esmail ebo...@hotmail.com wrote:
 Hi all,

 What is your favorite tool to help you debug your
 code? I've been getting along with 'print' statements
 but that is getting old and somewhat cumbersome.

 I'm primarily interested in utilities for Linux (but
 if you have recommendations for Windows, I'll take
 them too :)

 I use emacs as my primary development environment, FWIW.
 Someone mentioned winpdb .. anyone have experience/comments
 on this? Others?

 Thanks,
 Esmail

Although like the others I mostly use print statements, in a few
occasions I have found useful to resort to a full-blown debugger. Of
the ones I have used, the one provided by eclipse+pydev is the one I
liked most. The one in pywin32 IDE is basic but can be useful.
With emacs, one should be able to use pydb, but I never used that,
although emacs is my most used programming environment on most
platforms.

About print cumbersomeness, I agree. As I posted elsewhere, I'd like a
'trace mechanism' with the
following characteristics:
1. Can be enabled/disabled easily, and when it is dsabled it has no
runtime costs ( i.e. disabled 'trace' statements do not generate any
code)
2. Can be enabled/disabled on a class/function/method  base (e.g.
enable only the trace in a method ), to only get the trace output from
the code you are debugging
3. Make it easy to report the context (i.e. generate messages which
starts with 'class.method:', without
  hanving to hardcode class name and method name).

I know about the 'trace' and 'logging' modules, but neither seem to
satisfy the above requirements. Probably using python introspection
and metaprogramming features it is possible to do somethinmg that
covers at least 2 and 3. Not sure about one (using if __debug__ you
can reduce the runtime cost when
compiling in optimized mode, but probably not nullify it).

Ciao
-
FB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: conditional for-statement

2009-08-23 Thread Francesco Bochicchio
On Aug 23, 10:09 am, seb sdemen...@gmail.com wrote:
 Hi,

 i was wondering if there is a syntax alike:

 for i in range(10) if i  5:
     print i

 equivalent to

 for i in (for i in range(10) if i5):
     print i

 sebastien

AFAIK, no syntax fo that. But the standard syntax is not too
different:

for i in range(0):
if i  5 : print i

Or you can use itertools.ifilter:

for i in itertools.ifilter( lambda x: x  5, range(10) ):
 print i

Or, if you define a function corresponding to the loop body, you could
do something like:

map( print, (i for i in range(10) if i 5 )) # only works if print is
a function



Ciao

FB



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create ones own lib

2009-08-19 Thread Francesco Bochicchio
On 19 Ago, 11:00, Horst Jäger h.jae...@medienkonzepte.de wrote:
 Hi,

 I would like to create my own lib hotte.py which I can import like

         import string,hotte

 . How do I do that?

 I'm working on MacOS 10.5.6 .

 Thanks in advance

Just create the file 'hotte.py' and place it somewhere python can find
it, that is:
- in the same directory of the code using it (which is most probablyt
what you want to do )
- in a directory listed in  sys.path variable (which you can extend
using sys.path.append(full_path_of_my_library_directory) before
doing import hotte

There are other options, but these should cover your needs.

Ciao
-
FB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flatten a list of list

2009-08-16 Thread Francesco Bochicchio
On Aug 16, 1:25 pm, Steven D'Aprano st...@remove-this-
cybersource.com.au wrote:

...

 Chris' suggestion using itertools seems pretty good:

  from timeit import Timer
  setup = \\

 ... L = [ [None]*5000 for _ in xrange(%d) ]
 ... from itertools import chain
 ...  Timer(list(chain.from_iterable(L)), setup % 
 4).repeat(number=1000)

 [0.61839914321899414, 0.61799716949462891, 0.62065696716308594] 
 Timer(list(chain.from_iterable(L)), setup % 8).repeat(number=1000)

 [1.2618398666381836, 1.3385050296783447, 3.9113419055938721] 
 Timer(list(chain.from_iterable(L)), setup % 16).repeat(number=1000)

 [3.1349358558654785, 4.8554730415344238, 5.431217987061]

 --
 Steven

I had a peek at itertools ( which is a C module btw) and realized that
chain solves the problem by creating a chain object,
which is a sort of generator. Both creating the chain object and
converting the chain object to a list seem to be O(N), so
the whole is O(N) too ...

Then I tried this pure python version:

# - CODE
from timeit import Timer
setup = \\
L = [ [None]*5000 for _ in range(%d) ]
def pychain( list_of_list ):
for l in list_of_list:
for elem in l:
yield elem


print( Timer(list(pychain(L)), setup % 4).repeat(number=1000))
print( Timer(list(pychain(L)), setup % 8).repeat(number=1000))
print( Timer(list(pychain(L)), setup % 16).repeat(number=1000))
# - END CODE


and got times that seem to confirm it :

[2.818755865097046, 2.7880589962005615, 2.79232120513916]
[5.588631868362427, 5.588244915008545, 5.587780952453613]
[11.620548009872437, 11.39465618133545, 11.40834903717041]

For reference, here are the times of the itertools.chain solution on
my laptop:

[0.6518809795379639, 0.6491332054138184, 0.6483590602874756]
[1.3188841342926025, 1.3173959255218506, 1.3207998275756836]
[2.7200729846954346, 2.5402050018310547, 2.543621063232422]

All this with Python 3.1 compiled from source on Xubuntu 8.10.

Ciao
-
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does my ftp script quit after couple of hours?

2009-08-14 Thread Francesco Bochicchio
On 14 Ago, 18:03, kk maymunbe...@gmail.com wrote:
 Hi
 This way the first time I did something with ftp stuff. I think that
 generally it works but it stops working(quits or disappears) after
 couple of hours of running.

 This was a personal test-trial script for my own needs which was to
 get my dynamic ip and broadcast to a client(I have a client script on
 another computer). I sure could use something like DynDns for the same
 purpose with easier management but I just wanted to give it a try to
 see if i could even make it work .

 Basically this script parses my ip from DynDns ip check page and
 uploads it to the given ftp site. It works fine initially, it does
 upload, it updates the Ip every hour but the problem is that after
 couple of hours the Python console window disappears, I assume it
 crashes.  I know it does upload at least couple times(works for couple
 hours). it might be something to do with ftp connection. I will
 investigate that but I just wanted to see if I have any logic or some
 kind of contextual problem in the script.

 Here is the link to Pastie pagehttp://pastie.org/584152

 Thanks

Try catching the exception inside the main loop, to prevent your
program to exit in case of failure:

if __name__=='__main__':
  while True:
try:
writeExtFile(FILE_PATH,FILE_NAME)
uploadFile
(FTP_NAME,FTP_USER_NAME,FTP_PASSWD,FTP_FOLDER,FILE_NAME)
time.sleep(TIME_DELAY)
except:
  err, det, tb = sys.exc_info()
  print ERROR =, err, det # gives you a description of the
occurred failure
  traceback.print_tb(tb) # this might be needed only for debug


Ciao

FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable scoping question.

2009-08-10 Thread Francesco Bochicchio
On Aug 10, 5:12 pm, Diez B. Roggisch de...@nospam.web.de wrote:
 Cornelius Keller wrote:
  Hi,

  I'm a quite fresh python programmer, (6 Month python experience).
  Today I found something I absolotly don'nt understand:

  given the following function:

  def test_effect(class_id=None,class_ids=[]):
      if class_id is not None:
          if class_id not in class_ids:
              class_ids.append(int(class_id))

      print class_ids

  I observe that the class_ids array is growing when it is called with
  different class id's.

  I expected class_ids to be [] if the keyword argument is not set, but
  it seems to beahve like a static variable if not set.

 http://effbot.org/zone/default-values.htm

 Diez

Maybe on the first page of python.org there should be a 'python
gotchas' link to a page listing these few
non-intuituive peculiarities of our beloved snake ... same goes for
the official python tutorial ...

Ciao
-
FB

-- 
http://mail.python.org/mailman/listinfo/python-list


[issue6280] calendar.timegm() belongs in time module, next to time.gmtime()

2009-08-06 Thread Francesco Del Degan

Francesco Del Degan f.delde...@ngi.it added the comment:

Hi, i started to produce a patch for timemodule.c.

Working into it, i found that we have almost 3 way to do that:

1. Use timegm(3) function where HAVE_TIMEGM is defined (i have a working patch 
for it)

2. Implement a more portable timegm function with tzset and mktime where 
HAVE_MKTIME and 
HAVE_WORKING_TZSET is defined (i have a working patch for it)

3. Doing some calculation taking calendar.timegm as example.


What do you think about it?

Thanks,
Francesco pr0gg3d Del Degan

--
nosy: +pr0gg3d

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6280
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6596] urllib2 bug on CentOS

2009-08-03 Thread Francesco Del Degan

Francesco Del Degan f.delde...@ngi.it added the comment:

I don't think that this is a python issue, because of this:

[r...@localhost ~]# curl -O http://wm.exchanger.ru/asp/XMLWMList.asp?exchtype=1
  % Total% Received % Xferd  Average Speed   TimeTime Time  Current
 Dload  Upload   Total   SpentLeft  Speed
  0 00 00 0  0  0 --:--:-- --:--:-- --:--:-- 0
[r...@localhost ~]# curl -O http://wm.exchanger.ru/asp/XMLWMList.asp?exchtype=1
  % Total% Received % Xferd  Average Speed   TimeTime Time  Current
 Dload  Upload   Total   SpentLeft  Speed
100  9299  100  92990 0  15471  0 --:--:-- --:--:-- --:--:-- 22134


I done two request in rapid succession and into first i got a redirect to

0x:  4500 008f 3abb  3206 1d98 d49e ad94  E...:...2...
0x0010:  ac10 01d3 0050 b220 47ee 6cdb 8b3d 6233  .P..G.l..=b3
0x0020:  5011 0001 edc2  4854 5450 2f31 2e31  P...HTTP/1.1
0x0030:  2033 3032 204d 6f76 6564 2054 656d 706f  .302.Moved.Tempo
0x0040:  7261 7269 6c79 0d0a 436f 6e74 656e 742d  rarily..Content-
0x0050:  4c65 6e67 7468 3a20 300d 0a4c 6f63 6174  Length:.0..Locat
0x0060:  696f 6e3a 202f 6173 702f 584d 4c57 4d4c  ion:./asp/XMLWML
0x0070:  6973 742e 6173 703f 6578 6368 7479 7065  ist.asp?exchtype
0x0080:  3d31 3f34 6430 3266 3136 380d 0a0d 0a=1?4d02f168

as you can see, the ?4d02f168 part comes from the site, hence the 500 error 
from second request.

In the second try, i got correct response.

The weird thing is that into other systems, no curl request triggers a redirect 
from the site,
and in centOS only we have this weird behaviour.

--
nosy: +pr0gg3d

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6596
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6596] urllib2 bug on CentOS

2009-08-03 Thread Francesco Del Degan

Francesco Del Degan f.delde...@ngi.it added the comment:

Update: Now into the same system (CentOS) without any mod:

 import urllib2
 url = 'http://wm.exchanger.ru/asp/XMLWMList.asp?exchtype=1'
 t = urllib2.urlopen(url).read()

 t
'?xml version=1.0?.

i thinks that you should try to look for some bugs into CentOS 
distribution.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6596
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6557] urllib.urlopen creates bad requests when location header of 301 redirects contain spaces

2009-08-03 Thread Francesco Del Degan

Francesco Del Degan f.delde...@ngi.it added the comment:

urllib2 does escape spaces (and other characters too):

In [20]: 
u=urllib2.urlopen(http://sourceforge.net/project/showfiles.php?
group_id=16847package_id=13374)

In [21]: u.url
Out[21]: 'http://sourceforge.net/projects/xmlrpc-c/files/Xmlrpc-
c%20Super%20Stable/'

In [22]: u.read()[0:100]
Out[22]: '\n\n!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 
Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xh'

--
nosy: +pr0gg3d

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6557
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6635] Profiler doesn't print usage (indexError instead)

2009-08-03 Thread Francesco Del Degan

New submission from Francesco Del Degan f.delde...@ngi.it:

$ python -m profile
Usage: profile.py [-o output_file_path] [-s sort] scriptfile [arg] ...

$ python -m profile -s calls
Traceback (most recent call last):
  File 
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/runpy.py, 
line 122, in _run_module_as_main
__main__, fname, loader, pkg_name)
  File 
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/runpy.py, 
line 34, in _run_code
exec code in run_globals
  File 
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/profile.py, 
line 619, in module
main()
  File 
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/profile.py, 
line 614, in main
parser.print_usage()
  File 
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/optparse.py, 
line 1584, in print_usage
print file, self.get_usage()
  File 
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/optparse.py, 
line 1570, in get_usage
self.expand_prog_name(self.usage))
  File 
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/optparse.py, 
line 1547, in expand_prog_name
return s.replace(%prog, self.get_prog_name())
  File 
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/optparse.py, 
line 1542, in get_prog_name
return os.path.basename(sys.argv[0])
IndexError: list index out of range


This is triggered by an early override of sys.argv when usage() is called 
(Lib/profile.py:603):

if not sys.argv[1:]:
parser.print_usage()
sys.exit(2)

(options, args) = parser.parse_args()
sys.argv[:] = args

if (len(sys.argv)  0):
sys.path.insert(0, os.path.dirname(sys.argv[0]))
run('execfile(%r)' % (sys.argv[0],), options.outfile, options.sort)
else:
parser.print_usage()
return parser




In the else branch it tries to print usage but sys.argv[] were already 
overwritten.

Attached is the proposed patch (tested with 2.5, 2.6, 3.1).

--
components: Library (Lib)
files: python-profile-sysargv.patch
keywords: patch
messages: 91240
nosy: pr0gg3d
severity: normal
status: open
title: Profiler doesn't print usage (indexError instead)
type: behavior
versions: Python 2.5, Python 2.6, Python 3.1
Added file: http://bugs.python.org/file14639/python-profile-sysargv.patch

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6635
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: socket send

2009-07-31 Thread Francesco Bochicchio
On Jul 30, 10:16 pm, Jan Kaliszewski z...@chopin.edu.pl wrote:
 30-07-2009 o 12:29:24 Francesco Bochicchio bieff...@gmail.com wrote:

  On Jul 30, 5:52 am, NighterNet darkne...@gmail.com wrote:
  I am trying to figure out how to send text or byte in python 3.1. I am
  trying to send data to flash socket to get there. I am not sure how to
  work it.

  buff= 'id=' , self.id , ':balive=False\n'
  clientSock.send(buff);

  Try putting a 'b' before the constant string that you want to send:

   type(b'123')
  class 'bytes'

 It's true. In python '...' literals are for strings ('str' type) and
 b'...' literals are for binary data (bytes type).

 Sockets' send() and recv() need binary data ('bytes' objects).

  or use something like this to convert non constant strings (with only
  ASCII characters) into bytes:
   s = A non-constant string : %d  % n
   s
  'A non-constant string : 12 '
   type(s)
  class 'str'

 What???

 'str' type in Python 3.x IS NOT a type of non-constant strings and
 IS NOT a type of strings with only ASCII characters!

 'str' type in Python 3.x *is* the type of immutable ('constant') and
 Unicode character (Unicode, not only ASCII) strings. It's the same what
 'unicode' type in Python 2.x.


... unfortunate choice of words and not enough research on my part
here. WHat I meant was: if you want
to send via socket a constant string, use b...; if you want to send
via socket  a string that you
made out of variables (the non-constant string ) then you have to
convert it in bytes. Since I did not
now of the encode method, I tried other solutions, like the one-liner
using ord or using the struct
module. Obviously, encode is better.

My bad :-)

Ciao
---
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket send

2009-07-30 Thread Francesco Bochicchio
On Jul 30, 5:52 am, NighterNet darkne...@gmail.com wrote:
 I am trying to figure out how to send text or byte in python 3.1. I am
 trying to send data to flash socket to get there. I am not sure how to
 work it.

 buff= 'id=' , self.id , ':balive=False\n'
 clientSock.send(buff);

Try putting a 'b' before the constant string that you want to send:

 type(b'123')
class 'bytes'

or use something like this to convert non constant strings (with only
ASCII characters) into bytes:

 s = A non-constant string : %d  % n
 s
'A non-constant string : 12 '
 type(s)
class 'str'
 b = bytes ( ord(c) for c in s )
 b
b'A non-constant string : 12 '

You could also use struct.pack , that in python 3.x returns bytes and
not strings. In this case you need to specify the size of the string
(extra
bytes are zero-filled):

import struct

 struct.pack( 30s, A non-constant string : %d  % n )
b'A non-constant string : 12 \x00\x00\x00'



Ciao
-
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Python processors? : WAS Re: Does python have the capability for driver development ?

2009-07-30 Thread Francesco Bochicchio
On Jul 30, 11:10 am, Christian Heimes li...@cheimes.de wrote:
 Martin P. Hellwig wrote:
  Well the pyc, which I thought was the Python bytecode, is then
  interpreted by the VM.

 Python is often referred as byte-code interpreted language. Most modern
 languages are interpreted languages. The list [1] is rather long.
 Technically speaking even native code is interpreted by the micro code
 of most CPUs.

 [1]http://en.wikipedia.org/wiki/Interpreted_language
 [2]http://en.wikipedia.org/wiki/Microcode

Once upon a time there where lisp machines, whith processors designed
to fastly execute lisp code  ... I worked with one of them for 2
years.
I wonder: has anybody thought of making a python-machine, or at least
a processor able to directly execute high-level bytecode (LLVM-like?).
I think the main feature of such a machine should be hyper-fast hash
lookup. Then dynamic memory management hardware ...

Ciao
-
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No PyPI search for 3.x compatible packages

2009-07-30 Thread Francesco Bochicchio
On 30 Lug, 01:55, Neil Hodgson nyamatongwe+thun...@gmail.com wrote:
    There appears to be no way to search PyPI for packages that are
 compatible with Python 3.x. There are classifiers for 'Programming
 Language' including 'Programming Language :: Python :: 3' but that seems
 to be for implementation language since there are so many packages that
 specify C. There are a total of 109 packages classified with Python ::
 [3, 3.0, 3.1] out of a total of 4829 
 packages.http://pypi.python.org/pypi?:action=browseshow=allc=214c=533

    The search box appears to search for any word entered so a search
 like xml 3.0 or xml AND 3.0 does not help.

    Some packages include version information in the Py Version column of
 their download lists or embedded in the download file names. Projects
 are often constrained to a particular set of Python versions so need to
 choose packages that will work with those versions. It would be helpful
 if PyPI made this information more visible and searchable.

    Neil

Are you sure? I note that for example pygtk has as language tags both
C and python. So maybe a C extension
for python3 would have both C and python 3 as language tags.

I suspect that the 109 packages you found are the only ones obf the
4829 which works with python3 (but I hope
to be wrong ).

Ciao
-
FB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket send

2009-07-30 Thread Francesco Bochicchio
On 30 Lug, 18:06, NighterNet darkne...@gmail.com wrote:
 On Jul 30, 6:56 am, Mark Tolonen metolone+gm...@gmail.com wrote:





  NighterNet darkne...@gmail.com wrote in message

 news:55aba832-df6d-455f-bf34-04d37eb06...@i4g2000prm.googlegroups.com...

  I am trying to figure out how to send text or byte in python3.1. I am
   trying to send data to flashsocketto get there. I am not sure how to
   work it.

   buff= 'id=' , self.id , ':balive=False\n'
   clientSock.send(buff);
   --
  http://mail.python.org/mailman/listinfo/python-list

  Python3.1strings are Unicode (think characters not bytes).  When writing
  to files, sockets, etc. bytes must be used.  Unicode strings have an
  encode() method, where you can specify an appropriate encoding (ascii,
  latin-1, windows-1252, utf-8, etc.):

      clientSock.send(buff.encode('ascii'))

  When reading from thesocket, you can decode() the byte strings back into
  Unicode strings.

      data = clientSock.recv(1024).decode('ascii')

  -Mark

 I am not sure how to use struct package.
 Here an example for the input:
 {id:1,playername:guest,x:100,y:50}
 {id:2,playername:tester,x:100,y:50}

 struct.pack(? )

If your messages are ASCII, like it seems, forget about struct, which
is for 'binary' message format.
Format the string as you would in 2.6 ( using % or string.format for
instance ) and then use encode
as instructed.


-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >