Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-07-24 Thread Lacrima
Hi!

I have two super classes:

class SuperClass1(object):
def __init__(self, word):
print word

class SuperClass2(object):
def __init__(self, word, word2):
print word, word2

Also I have subclass of these classes:

class SubClass(SuperClass1, SuperClass2):
def __init__(self):
pass

I have two questions.
1) Inside __init__ of SubClass how can I firstly call __init__ of
SuperClass1, and then __init__ of SuperClass2, using builtin super()
function.
2) Why should I use super() at all, if it is very easy to call methods
of super class like this:
class SubClass(SuperClass1, SuperClass2):
def __init__(self):
SuperClass1.__init__(self, 'Python')
SuperClass2.__init__(self, 'Hello', 'world')

Thanks in advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-07-24 Thread Lacrima
On Jul 24, 11:20 am, Raymond Hettinger raymond.hettin...@gmail.com
wrote:
 On Jul 24, 12:47 am, Lacrima lacrima.ma...@gmail.com wrote:



  Hi!

  I have two super classes:

  class SuperClass1(object):
      def __init__(self, word):
          print word

  class SuperClass2(object):
      def __init__(self, word, word2):
          print word, word2

  Also I have subclass of these classes:

  class SubClass(SuperClass1, SuperClass2):
      def __init__(self):
          pass

  I have two questions.
  1) Inside __init__ of SubClass how can I firstly call __init__ of
  SuperClass1, and then __init__ of SuperClass2, using builtin super()
  function.

 I would write it like this:

 class SuperClass1(object):
     def __init__(self, **kwds):
         word = kwds.pop('word')
         print word
         super(SuperClass1, self).__init__(**kwds)

 class SuperClass2(object):
     def __init__(self, **kwds):
         word1 = kwds.pop('word1')
         word2 = kwds.pop('word2')
         print word1, word2
         super(SuperClass2, self).__init__(**kwds)

 class SubClass(SuperClass1, SuperClass2):
     def __init__(self, **kwds):
         super(SubClass, self).__init__(**kwds)

 SubClass(word='Python', word1='Hello', word2='World')

  2) Why should I use super() at all, if it is very easy to call methods
  of super class like this:
  class SubClass(SuperClass1, SuperClass2):
      def __init__(self):
          SuperClass1.__init__(self, 'Python')
          SuperClass2.__init__(self, 'Hello', 'world')

 That works just fine in this case.
 The challenge arises in diamond diagrams
 such as A-B  A-C  B-D  C-D where both B and C
 are written independently of D and both need to call
 A's __init__ but that method should only be called
 once (not once by B and again by C).

 In that case, the super() pattern shown above will
 let each parent's method be called exactly once
 and guarantee that parents are called before grandparents
 and guarantee that the left-to-right ordering of multiple
 bases is respected.

 Raymond

Hi, Raymond!

Thank you for your answer.

Some things are still not clear. Your example works great. But if I
remove super(SuperClass1, self).__init__(**kwds) from SuperClass1's
__init__, the example stops working. That is when I instantiate
SubClass only __init__ of SuperClass1 is called and __init__ of
SuperClass2 is omitted, i.e. only 'Python' is printed. Why is it so?

So as I understand every parent should necessarily call super() at the
end of its __init__ method in order for things to work properly.

But what if SuperClass1 is from third party library? Then I can't
modify it to follow this convention, that is when I instantiate my
SubClass only __init__ from SuperClass1 will be called, and __init__
from SuperClass2 will be omitted.
How to deal with that?

My post is quite intricate, but this is because of my English. Sorry.

Looking forward for help. Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


String Formatting Operations for decimals.

2010-04-01 Thread Lacrima
Hello!

I need to format a decimal (floating point) number in the following
way:
10 results in '10'
10.5 results in '10.5'
10.50 results in '10.5'
10.5678 results in 10.57

How can I achieve this using standard Python string formatting
operations?
Something like '%.2f' works almost as expected:
 '%.2f' % 10.5
'10.50'
 '%.2f' % 10.5678
'10.57'
 '%.2f' % 10
'10.00'
But I always need trailing zeros to be excluded, i.e. 10.5 should
result in '10.5' (not '10.50'), and 10 should result in '10' (not
'10.00').
So how can I do this?
Sorry for my English.
Thanks in advance.

with regards,
Maxim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Formatting Operations for decimals.

2010-04-01 Thread Maxim Lacrima
Hello, Chris!

Thanks for your really quick reply! It works!


On 1 April 2010 12:14, Chris Rebert c...@rebertia.com wrote:

 On Thu, Apr 1, 2010 at 2:08 AM, Lacrima lacrima.ma...@gmail.com wrote:
  Hello!
 
  I need to format a decimal (floating point) number in the following
  way:
  10 results in '10'
  10.5 results in '10.5'
  10.50 results in '10.5'
  10.5678 results in 10.57
 
  How can I achieve this using standard Python string formatting
  operations?
  Something like '%.2f' works almost as expected:
  '%.2f' % 10.5
  '10.50'
  '%.2f' % 10.5678
  '10.57'
  '%.2f' % 10
  '10.00'
  But I always need trailing zeros to be excluded, i.e. 10.5 should
  result in '10.5' (not '10.50'), and 10 should result in '10' (not
  '10.00').
  So how can I do this?

 ('%.2f' % 10).rstrip('0').rstrip('.')

 Cheers,
 Chris
 --
 http://blog.rebertia.com




-- 
with regards,
Maxim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Advanced Python Programming Oxford Lectures [was: Re: *Advanced* Python book?]

2010-03-27 Thread Lacrima
On Mar 26, 10:22 am, Michele Simionato michele.simion...@gmail.com
wrote:
 On Mar 25, 2:24 pm, Michele Simionato michele.simion...@gmail.com
 wrote:

  On Mar 25, 1:28 pm, Ethan Furman et...@stoneleaf.us wrote:

   Michele,

   Was wondering if you'd had a chance to re-post your lectures -- just did
   a search for them and came up empty, and I would love to read them!

   Many thanks in advance!

  Oops, I forgot! I will try to make them available soon.

 Here they are:http://www.phyast.pitt.edu/~micheles/oxford-lectures.zip

Hello, Michele!
Thanks a lot for posting!!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Can't install ssl for Python2.5

2010-03-10 Thread Lacrima
Hello!

I use Ubuntu 9.10 Karmic Koala. It has Python 2.6 as default
installation.
And I installed Python 2.5 alongside (for the need of Google
AppEngine). But it seems like my Python 2.5 installation lacks ssl
support. I can't import ssl and starting appengine server fails with
'module' object has no attribute 'HTTPSHandler'.
So I tried to install this: http://pypi.python.org/pypi/ssl/1.15
But it failed with a very strange error:
sudo easy_install-2.5 ssl
-
Searching for ssl
Reading http://pypi.python.org/simple/ssl/
Reading http://docs.python.org/dev/library/ssl.html
Best match: ssl 1.15
Downloading 
http://pypi.python.org/packages/source/s/ssl/ssl-1.15.tar.gz#md5=81ea8a1175e437b4c769ae65b3290e0c
Processing ssl-1.15.tar.gz
Running ssl-1.15/setup.py -q bdist_egg --dist-dir /tmp/easy_install-
Kd839q/ssl-1.15/egg-dist-tmp-QCIl6J
looking for /usr/include/openssl/ssl.h
looking for /usr/local/ssl/include/openssl/ssl.h
looking for /usr/include/krb5.h
looking for /usr/kerberos/include/krb5.h
error: Setup script exited with error: SandboxViolation: open('/usr/
local/lib/python2.5/test/test_ssl.py', 'wb') {}

The package setup script has attempted to modify files on your system
that are not within the EasyInstall build area, and has been aborted.

This package cannot be safely installed by EasyInstall, and may not
support alternate installation locations even if you run its setup
script by hand.  Please inform the package's author and the
EasyInstall
maintainers to find out if a fix or workaround is available.
-

I don't know how to solve this problem and I am looking forward for
help.
Thanks in advance.

with regards,
Maxim.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't install ssl for Python2.5

2010-03-10 Thread Lacrima
On Mar 10, 11:23 pm, Martin v. Loewis mar...@v.loewis.de wrote:
  I don't know how to solve this problem and I am looking forward for
  help.

 Try running python setup.py install directly, after downloading and
 unpacking the package.

 Regards,
 Martin

Thanks a lot! It helped!
-- 
http://mail.python.org/mailman/listinfo/python-list


Using mock library (written by Michael Foord)

2010-02-25 Thread Lacrima
Hello!

I use mock library http://www.voidspace.org.uk/python/mock/. There is
no user group for the library, so I post in comp.lang.python and hope
that people who use it will help me.

The library allows to patch objects, using patch decorator. Patching
is done only within the scope of the function. So if I have a lot of
tests that need specific object to be patched I have to specify the
same decorator for each test method:

class TestSomething(unittest.TestCase):

@patch('module.Class', spec = True)
def test_method1(self, MockClass):
Class()
self.assertEquals(MockClass.called)

@patch('module.Class', spec = True)
def test_method2(self, MockClass):
Class()
MockClass.assert_called_with('foo')

@patch('module.Class', spec = True)
 def test_method3(self, MockClass):
foo = Class()
self.assertRaises(AttributeError, foo.some_method)

# and more ...

So for every test method I always do the same patching! How can I
avoid this?

Thanks in advance.
Sorry if my English isn't proper enough.

With regards,
Maxim.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which mock library do you prefer?

2010-02-21 Thread Lacrima
On Feb 18, 3:20 am, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Lacrima lacrima.ma...@gmail.com writes:
  Right, isolation [of test cases] is essential. But I can't decide to
  which extent I should propagate isolation.

 You used “propagate” in a sense I don't understand there.

  For example, in Python Testing: Beginner's Guide by Daniel Arbuckle,
  author suggests that if you do unittesting you should isolate the
  smallest units of code from each other.

 I'm not sure what the author means, but I would say that as it stands
 that advice is independent of what testing is being done. In all cases:

 * Make your code units small, so each one is not doing much and is easy
   to understand.

 * Make the interface of units at each level as narrow as feasible, so
   they're not brittle in the face of changes to the implementation.

  For example, if you have a
  class:
  Class SomeClass(object):
      def method1(self):
          return 5
      def method2(self):
          return self.method1 + 10

  According to the book, if you want to test method2, you should isolate
  it from method1 and class instance('self').

 I don't really know what that means.

 Remember that each test case should not be “test method1”. That is far
 too broad, and in some cases too narrow. There is no one-to-one mapping
 between methods and unit test cases.

 Instead, each test case should test one true-or-false assertion about
 the behaviour of the code. “When we start with this initial state (the
 test fixture), and perform this operation, the resulting state is that”.

 It makes a lot of sense to name the test case so the assertion being
 made *is* its name: not ‘test frobnicate’ with dozens of assertions, but
 one ‘test_frobnicate_with_valid_spangulator_returns_true’ which makes
 that assertion, and extra ones for each distinct assertion.

 The failure of a unit test case should indicate *exactly* what has gone
 wrong. If you want to make multiple assertions about a code unit, write
 multiple test cases for that unit and name the tests accordingly.

 This incidentally requires that you test something small enough that
 such a true-or-false assertion is meaningful, which leads to
 well-designed code with small easily-tested code units. But that's an
 emergent property, not a natural law.

  Currently, I don't create mocks of units if they are within the same
  class with the unit under test. If that is not right approach, please,
  explain what are best practices... I am just learning TDD..

 In the fixture of the unit test case, create whatever test doubles are
 necessary to put your code into the initial state you need for the test
 case; then tear all those down whatever the result of the test case.

 If you need to create great honking wads of fixtures for any test case,
 that is a code smell: your code units are too tightly coupled to
 persistent state, and need to be decoupled with narrow interfaces.

 The Python ‘unittest’ module makes this easier by letting you define
 fixtures common to many test cases (the ‘setUp’ and ‘tearDown’
 interface). My rule of thumb is: if I need to make different fixtures
 for some set of test cases, I write a new test case class for those
 cases.

 --
  \       “Following fashion and the status quo is easy. Thinking about |
   `\        your users' lives and creating something practical is much |
 _o__)                                harder.” —Ryan Singer, 2008-07-09 |
 Ben Finney

Hi, Ben!!!

Sorry for too late reply!!!
Thank you very much for sharing your experience! I still have to grasp
a lot in TDD.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which mock library do you prefer?

2010-02-17 Thread Lacrima
On Feb 16, 7:38 pm, Phlip phlip2...@gmail.com wrote:

 This paper _almost_ gets the 
 idea:http://www.netobjectives.com/download/Code%20Qualities%20and%20Practi...


 Do you run your tests after the fewest possible edits? Such as 1-3
 lines of code?


Hi!
I run my tests all the time (they almost replaced debugger in my IDE).
But there are times, when I can't just run tests after 1-3 lines of
code.
For example, I am developing an application that talks to some web
service. One of methods of a class, which implements API for a given
web service, should parse xml response from web service. At first, I
hardcoded returned values, so that they looked like already parsed.
But further, additional tests forced me to actually operate with
sample xml data instead of hardcoded values. So I created sample xml
file that resembled response from server. And after that I can't just
write 1-3 lines between each test. Because I need to read() the file
and sort it out in a loop (at least 6-9 lines of code for small xml
file). And only after this procedure I run my tests with the hope that
they all pass.
Maybe it's not proper TDD, but I can't figure out how to reduce period
between running tests in a case above.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which mock library do you prefer?

2010-02-17 Thread Lacrima
On Feb 16, 10:30 pm, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Lacrima lacrima.ma...@gmail.com writes:
  And I have already refused to write totally isolated tests, because it
  looks like a great waste of time.

 It only looks like that until you chase your tail in a long, fruitless
 debugging session because (you later realise) the behaviour of one test
 is being affected by another. Test isolation is essential to ensure that
 your tests are doing what you think they're doing.

 --
  \       “A ‘No’ uttered from deepest conviction is better and greater |
   `\       than a ‘Yes’ merely uttered to please, or what is worse, to |
 _o__)                              avoid trouble.” —Mohandas K. Gandhi |
 Ben Finney

Hi!

Right, isolation is essential. But I can't decide to which extent I
should propagate isolation.
For example, in Python Testing: Beginner's Guide by Daniel Arbuckle,
author suggests that if you do unittesting you should isolate the
smallest units of code from each other. For example, if you have a
class:
Class SomeClass(object):
def method1(self):
return 5
def method2(self):
return self.method1 + 10

According to the book, if you want to test method2, you should isolate
it from method1 and class instance('self').
Other books are not so strict...

And what should I follow as newbie?

Currently, I don't create mocks of units if they are within the same
class with the unit under test. If that is not right approach, please,
explain what are best practices... I am just learning TDD..

with regards,
Maxim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which mock library do you prefer?

2010-02-16 Thread Lacrima
On Feb 16, 2:17 am, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Lacrima lacrima.ma...@gmail.com writes:
  Minimock has wider usage and community, but I have some troubles using
  it. Maybe I am wrong, but with minimock you always have to keep track
  the order of imports in your test modules. Well, may be I just don't
  understand fully how minimock works.

 I'm not sure why you think you need to keep track of the order of
 imports.

 Simply set up the mocks as you want them, in your fixtures; then, when
 tearing down your fixtures, use ‘minimock.restore()’ to restore the
 affected namespaces to their initial state.

 --
  \       “… one of the main causes of the fall of the Roman Empire was |
   `\        that, lacking zero, they had no way to indicate successful |
 _o__)                  termination of their C programs.” —Robert Firth |
 Ben Finney

Hi Ben!

See these two topics:
http://groups.google.com/group/minimock-dev/browse_thread/thread/bcbb3b7cc60eb96f
http://groups.google.com/group/minimock-dev/browse_thread/thread/c41cd996735ea1a6

There are special cases, which you have to be aware of, if you use
minimock.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which mock library do you prefer?

2010-02-16 Thread Lacrima
On Feb 15, 9:56 pm, Phlip phlip2...@gmail.com wrote:
 Lacrima wrote:
  Thanks for your reply! Isn't what you are talking about integration
  tests? And unit tests should be fully isolated? So even for method
  'some_method()' of class A I should mock instance of class A (i.e. to
  mock 'self') to test 'some_method()'.

 Unit test is a high-end QA concept. Developers can get the best
 return on developer tests. They don't bother with aerospace-quality
 isolation between units.

 If a TDD test needs to pull in a bunch of modules to pass, that's
 generally a good thing, because they all get indirect testing. If they
 catch a bug, their local tests might not catch it, but the higher
 level tests still have a chance.

 (And if your product still needs unit tests, TDD will make them very
 easy for a formal QA team to add.)

 However, expensive setup is a design smell. That means if a test case
 requires too many lines of code for its Assemble phase (before its
 Activate and Assert phases), then maybe those lines of code support
 objects that are too coupled, and they need a better design.

 Throwing mocks at these objects, instead of decoupling them, will
 perfume the design smell, instead of curing it.

   construction encapsulation)
  And could you give an example.

   def test_frob(self):
       frob = Frob()
       frob.knob = Mock()
       frob.knob.value = Mock(return_value = 42)
       assert 42 == frob.method_using_knob()

 We need the mock because we can't control how Frob's constructor built
 its knob. So instead, give Frob the option to construct with a Knob:

   def test_frob(self):
       knob = Knob(42)
       frob = Frob(knob)
       assert frob.method_using_knob()

 Note that in production the Knob constructor never takes a Knob. Maybe
 we should upgrade the production code too (!), or maybe Knob's
 constructor should only create a knob if it didn't get passed one.
 Either technique is acceptable, because the resulting code decouples
 Frobs and Knobs just a little bit more.

  For me it's really hard to develop test first. Often I don't know what
  tests to write to replace hardcoded return values by objects that
  perform actual work.

 You have read too many books on TDD. C-:

 Alternate between writing lines of test and lines of code. Run the
 tests after the fewest possible edits, and always correctly predict if
 the tests will pass, or will fail, and with what diagnostic. (And
 configure your editor to run the stankin tests, no matter how hard it
 fights you!) The high-end tricks will get easier after you get the
 basic cycle down.

 --
   Phlip
  http://c2.com/cgi/wiki?ZeekLand

Hi Phlip!

Thanks for your exhaustive answer.
Actually, I'll investigate your example with 'frob'. From just reading
the example it's not clear for me what I will benefit, using this
approach.
And I have already refused to write totally isolated tests, because it
looks like a great waste of time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Which mock library do you prefer?

2010-02-15 Thread Lacrima
Hello!

I am newbie mastering test driven development. I can't clarify myself
which mock library to use.
There are number of them and which one do you prefer?

Two libraries that attracted my attention are:
* minimock
* dingus
As for me the latest one, dingus, is the easiest (see this screencast:
http://vimeo.com/3949077   ), but it has very few downloads from pypi,
so it scares me a little.
Minimock has wider usage and community, but I have some troubles using
it. Maybe I am wrong, but with minimock you always have to keep track
the order of imports in your test modules. Well, may be I just don't
understand fully how minimock works.

What are your suggestions?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which mock library do you prefer?

2010-02-15 Thread Lacrima
On Feb 15, 6:57 pm, Phlip phlip2...@gmail.com wrote:
 Lacrima wrote:
  I am newbie mastering test driven development. I can't clarify myself
  which mock library to use.
  There are number of them and which one do you prefer?

  Two libraries that attracted my attention are:
  * minimock
  * dingus
  As for me the latest one, dingus, is the easiest (see this 
  screencast:http://vimeo.com/3949077 ), but it has very few downloads from 
  pypi,
  so it scares me a little.
  Minimock has wider usage and community, but I have some troubles using
  it. Maybe I am wrong, but with minimock you always have to keep track
  the order of imports in your test modules. Well, may be I just don't
  understand fully how minimock works.

  What are your suggestions?

 I have usedhttp://pypi.python.org/pypi/mock/0.6.0. It mocks, and it
 has a mode that works one method at a time, and another mode that
 mocks a method before its owning object gets constructed.

 However, TDD is not about mocking, and on greenfield code you should
 only mock to recover from some external problem, such as:

  - a random number generator
  - the system clock
  - anything over the wire - over a TCP/IP socket
  - hardware, such as your graphics or sound

 Never mock to avoid hitting the database. Some TDD verbiage advises
 never hit the database. That is a mind-game to force you to decouple
 your code. Your objects should always have the option (via
 construction encapsulation) to run as stubs, with some of their
 behaviors turned off. And if you TDD low-level code that hits a
 database, a mock would only tell the test what it wants to hear. And
 if you TDD high-level code that manages business rules, database
 records make perfectly good behavioral fixtures to support those
 rules.

 --
   Phlip
  http://c2.com/cgi/wiki?ZeekLand

Hi, Phlip!

Thanks for your reply! Isn't what you are talking about integration
tests? And unit tests should be fully isolated? So even for method
'some_method()' of class A I should mock instance of class A (i.e. to
mock 'self') to test 'some_method()'.

Please, could you explain in more detail your thoughts:
 Your objects should always have the option (via
 construction encapsulation) to run as stubs, with some of their
 behaviors turned off. And if you TDD low-level code that hits a
 database, a mock would only tell the test what it wants to hear. And
 if you TDD high-level code that manages business rules, database
 records make perfectly good behavioral fixtures to support those
 rules.

And could you give an example.
For me it's really hard to develop test first. Often I don't know what
tests to write to replace hardcoded return values by objects that
perform actual work.
I have read several books on TDD and explored 
http://c2.com/cgi/wiki?TestDrivenDevelopment
and related wikis, but often it seems I don't have enough
understanding to write even simple application.
And sorry for my English.

with regards,
Max.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what test runner should I use?

2010-01-21 Thread Lacrima
On Jan 19, 12:56 pm, Chris Withers ch...@simplistix.co.uk wrote:
 Hi All,

 I'm wondering what test runner I should use. Here's my list of requirements:

 - cross platform (I develop for and on Windows, Linux and Mac)

 - should not prevent tests from running with other test runners
    (so no plugins/layers/etc that only work with one specific test
     runner)

 - should work with zc.buildout (preferably without a specialist recipe!)

 So far I've tried the following with the resultant problems:

 zope.testing

   - requires a special recipe to be useful
   - now emits deprecation warnings from itself:
    https://mail.zope.org/pipermail/zope-dev/2009-December/038965.html
   - coverage support is baroque to put it politely

 twisted's trial

   - only has old-style script definition in setup.py, so doesn't work
     with buildout without hackery

   - drops _twisted_trial folders all over the place and doesn't clear
     them up

 nose

   - can't see to get it to run only my packages tests, rather than
     including the tests of packages my package depends on

   - seems to be focused towards files rather than modules
     (which makes it not play nicely with buildout)

   - seems to be difficult to provide options to at configuration time
     that can then be overridden on the command line

 I did also look at py.test's homepage but found it pretty scary.

 What other options do people recommend?
 Failing that, any ideas how to fix the problems above?

 cheers,

 Chris

Nose should work pretty well with buildout. You need this in your
buildout.cfg

[buildout]
parts = test

[test]
recipe = pbp.recipe.noserunner
eggs = yourpackage1 yourpackage2

This will generate test script (bin/test), which will search and run
tests only in packages, specified in eggs option.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anybody use web2py?

2009-12-21 Thread Lacrima
On Dec 20, 1:35 am, mdipierro massimodipierr...@gmail.com wrote:
 Errata. I said The dal supports transactions where I meant the dal
 supports migrations.
 Of course it also supports transactions as well as distributed
 transactions.


Sorry, if this is not related to this topic.
Does web2py support distributed transactions with Google App Engine
Datastore?
-- 
http://mail.python.org/mailman/listinfo/python-list


TDD with nose or py.test

2009-11-30 Thread Lacrima
Hello!

I am learning TDD with Python and there is not much information about
this topic. Python is shipped with unittest module. That is fine, but
I also discovered other libraries: nose and py.test. They promise to
make life yet easier for a developer. But I still can't figure out,
which combination I should use them in.
Nose seems simpler than py.test, but py.test offers more features. And
both py.test and nose say that they do not replace unittest module,
but extend it.
So as I understand my choice should be nose + unittest, or py.test +
unittest.
And now I'd like to hear about best practices in TDD in Python. Maybe
not best practices, but basic approach.
So which tests should I write with unittest, which with nose or
py.test? How should I combine them?

I am learning Python and I need your advice.
Thanks in advance.

Sorry if my English isn't very proper
-- 
http://mail.python.org/mailman/listinfo/python-list


Sqlite3. Substitution of names in query.

2009-10-30 Thread Lacrima
Hello!

I use sqlite3 module for my sqlite database. I am trying to substitute
table name in sql query.

 import sqlite3
 con = sqlite3.connect('mydb')
 cur = con.execute(select * from table where name='Joe')
That's ok

 cur = con.execute(select * from table where name=?, ('Joe',))
That's ok too

 cur = con.execute(select * from ? where name=?, ('table', 'Joe'))
Traceback (most recent call last):
  File string, line 1, in fragment
sqlite3.OperationalError: near ?: syntax error

So what's wrong now?
Is it impossible to substitute table names, using DB API?
If so, what is a way to make table name substitutions? Are string
operations like
'select * from %s where...' % tablename
ok in this case?

Thanks in advance!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: anydbm, gdbm, dbm

2009-10-28 Thread Lacrima
On Oct 27, 4:36 pm, Tim Chase python.l...@tim.thechases.com wrote:
 Lacrima wrote:
  I want to store some data, using anydbm module.
  According to docs the object returned by anydbm.open() supports most
  of the same functionality as dictionaries; keys and their
  corresponding values can be stored, retrieved, and deleted...

  I don't understand how I can make a table in DBM database, or a row in
  a table. Or all data must be stored just as key-value pairs?

 Yes, all data for the dbm variants is purely string-string
 mapping pairs.  Similarly, dictionaries don't natively allow you
 to store columns in them...they are just key-value data-stores.

  Suppose my table consists of two columns: 'first name' and 'last
  name'. How can I make such table and write there first and last names
  for, say, two any persons?

 *dbm provides no columns unless you hack them such as

    db[key] = DELIMITER.join([lastname, firstname])

 and then unhack them:

    lastname, firstname = db[key].split(DELIMITER, 1)

 As a variant of this, you might be able to use pickle/shelve to
 stash your multi-content object as a string-value.

 Alternatively, you could use something like

    db[%s_first % key] = firstname
    db[%s_last % key] = lastname

 assuming your keys didn't confound you.

 -tkc

Hi!

Thanks a lot! You've helped me very much!
-- 
http://mail.python.org/mailman/listinfo/python-list


anydbm, gdbm, dbm

2009-10-27 Thread Lacrima
Hello!

I want to store some data, using anydbm module.
According to docs the object returned by anydbm.open() supports most
of the same functionality as dictionaries; keys and their
corresponding values can be stored, retrieved, and deleted...

I don't understand how I can make a table in DBM database, or a row in
a table. Or all data must be stored just as key-value pairs?

Suppose my table consists of two columns: 'first name' and 'last
name'. How can I make such table and write there first and last names
for, say, two any persons?

Thanks in advance...
-- 
http://mail.python.org/mailman/listinfo/python-list


Design question.

2009-07-20 Thread Lacrima
Hello!

I am newbie in python and I have really simple question, but I need
your advice to know how to do best.
I need to store a number of dictionaries in certain place. I've
decided to store them in a separate module.
Like this:
dicts.py
---
dict1 = {}
dict2 = {}
dict3 = {}

Then, when I need any dictionary, I can access it:
import dicts
dicts.dict1

Is it a good practice? Or should I store them as class attributes or
anything else?

Thanks in advance.

With regards, Max
(sorry if my English isn't very proper)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Design question.

2009-07-20 Thread Lacrima
On Jul 20, 3:31 pm, Diez B. Roggisch de...@nospam.web.de wrote:
 Lacrima wrote:
  Hello!

  I am newbie in python and I have really simple question, but I need
  your advice to know how to do best.
  I need to store a number of dictionaries in certain place. I've
  decided to store them in a separate module.
  Like this:
  dicts.py
  ---
  dict1 = {}
  dict2 = {}
  dict3 = {}

  Then, when I need any dictionary, I can access it:
  import dicts
  dicts.dict1

  Is it a good practice? Or should I store them as class attributes or
  anything else?

 It's perfectly fine to use dictionaries as module-level objects for storing
 e.g. configuration-data.

 OTOH it's also fine to do so as class-attributes. Choosing one over the
 other has a lot to do with the actual problem you are working on.

 Diez

Hi!

Thank you very much for your so soon reply!

With regards,
Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Design question.

2009-07-20 Thread Lacrima
On Jul 20, 4:05 pm, Jean-Michel Pichavant jeanmic...@sequans.com
wrote:
 Lacrima wrote:
  Hello!

  I am newbie in python and I have really simple question, but I need
  your advice to know how to do best.
  I need to store a number of dictionaries in certain place. I've
  decided to store them in a separate module.
  Like this:
  dicts.py
  ---
  dict1 = {}
  dict2 = {}
  dict3 = {}

  Then, when I need any dictionary, I can access it:
  import dicts
  dicts.dict1

  Is it a good practice? Or should I store them as class attributes or
  anything else?

  Thanks in advance.

  With regards, Max
  (sorry if my English isn't very proper)

 Defining dict as a module attribute ic correct, but try to answer the
 following question:

 Is dict1 an attribute/property/declension of the object/entity defined
 by the module dicts ?
 If yes, then your design is correct.

 An correct example:
 fruits.py
 
 apple = {}
 banana = {}

 An incorrect one:
 fruit.py
 ---
 apple={}
 bicycle={}

 Basically, the rule is very straightforward, set your dict as a module
 attribute only if its one of its attribute (very nice paraphrase !)
 Most of people (including me) tend to have a  module, where they put
 everything they have no idea about their location. This is a bad habit
 and result from a uncontrolled/undocumented design. Usually documenting
 objects in such modules is really painful.

 Your proposal is fine from a python syntax point of view. I can't tell
 of your design with names like (dicts.py and dict1,dict2) hoping you do
 not intend to name them that way.

 JM

Hi, Jean-Michel!

Thanks for your answer.
I am not going to have names like dicts.py and dict1,dict2. That was
just example. I wanted to know if it is correct to have dictionaries
on a module level. Now I know that this is correct. I want to collect
in one module a number of dictionaries, every of which describes a
separate web service. And my function in another module will import
required dictionary, depending on what web service should be used.
Thanks again for the help.

With regards,
Max.
(sorry if my English isn't very proper)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib with x509 certs

2009-07-17 Thread Lacrima
Hello!

I've solved this problem, using pyCurl.
Here is sample code.

import pycurl
import StringIO
b = StringIO.StringIO()
c = pycurl.Curl()
url = 'https://example.com/'
c.setopt(pycurl.URL, url)
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.setopt(pycurl.CAINFO, 'cert.crt')
c.setopt(pycurl.SSLKEY, 'mykey.key')
c.setopt(pycurl.SSLCERT, 'mycert.cer')
c.setopt(pycurl.SSLKEYPASSWD , 'pass phrase')
c.perform()

This also allow to specify CA, so your requests are more secure then
with urllib.

With regards, Max.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Emacs Python-mode. Newbie problem.

2009-07-09 Thread Lacrima
On Jul 8, 10:54 pm, Piet van Oostrum p...@cs.uu.nl wrote:
  Lacrima lacrima.ma...@gmail.com (L) wrote:
 L Hello!
 L I have just started using Emacs to write python scripts.
 L I installed python-mode.el
 L Then I just tried this code:
 L print 'hello world'
 L When I press C-c RET, new blank window is opened and emacs says:
 L (Shell command succeeded with no output)
 L So where is my 'hello world'?
 L When I do C-c C-c, it prints 'hello world' successfully.
 L Why in the first case I get no output?

 Can you check in the buffer where you have the python code what command
 C-c RET is bound to?
 With C-h k C-c RET

 Shell command succeeded with no output suggests that is has a different
 binding than the standard one in python-mode.

 Did you happen to name your file 'test' or 'test.py?

 C-c RET does an import and 'import test' imports a standard module test.
 --
 Piet van Oostrum p...@cs.uu.nl
 URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
 Private email: p...@vanoostrum.org

Hi, Piet!

Thanks for your reply!
My file name is 'trains.py'.
When I do C-h k C-c RET, it shows me help from manual: C-c RET runs
the command py-execute-import-or-reload
   which is an interactive Lisp function in `python-mode'... and so
on.

And still when I do C-c RET, I receive (Shell command succeeded with
no output)

Any more help would be really appreciated, because I am newbie with
Emacs.

With regards, Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Emacs Python-mode. Newbie problem.

2009-07-09 Thread Lacrima
On Jul 9, 2:31 pm, Piet van Oostrum p...@cs.uu.nl wrote:
  Lacrima lacrima.ma...@gmail.com (L) wrote:
 L Thanks for your reply!
 L My file name is 'trains.py'.
 L When I do C-h k C-c RET, it shows me help from manual: C-c RET runs
 L the command py-execute-import-or-reload
 L    which is an interactive Lisp function in `python-mode'... and so
 L on.
 L And still when I do C-c RET, I receive (Shell command succeeded with
 L no output)
 L Any more help would be really appreciated, because I am newbie with
 L Emacs.

 I tested it and I can get this message also. It happens when you have no
 Python shell running (*Python* buffer). The python code is then executed
 by calling the python shell command and catching the output. This output
 is displayed in the *Python Output* buffer. It happens also with C-c C-c
 and it will give the same message.

 There is a difference, however between C-c C-x and C-c RET: The latter
 will import your module, and most modules are written such that
 importing them doesn't print anything. If you add something like
 print test and the end of file, then test will appear in the *Python
 Output*  buffer.

 If your file has the print hello world statement it should display in
 the *Python Output* buffer. I checked that.

 On the other hand, if you have a python shell running you must make sure
 (e.g. with the cd command) that its working directory is the directory
 where your python file is located, otherwise the import statement will
 not find your file. Unless it is somewhere in the python path. Also the
 *Python* buffer will not automatically pop up if it is not visible, in
 contrast with the *Python Output* buffer.
 --
 Piet van Oostrum p...@cs.uu.nl
 URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
 Private email: p...@vanoostrum.org

Thank you for really useful and detailed explanation. Now I can test
my code using Emacs.
But I think it works for me in a little bit different way.
My file contains only the print 'hello world'.
If I have no python shell running, then:
a) C-c RET opens *Python Output* buffer without any output and with
'Shell command succeeded with no output' message at the bottom
b) C-c C-c opens *Python Output* with appropriate 'hello world'
message.

Then I run python shell with C-c ! command. And:
a) C-c RET opens *Python* buffer and prints 'hello world' in the
python shell
b) C-c C-c gives the same result.

With regards, Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Emacs Python-mode. Newbie problem.

2009-07-09 Thread Lacrima
On Jul 9, 8:42 pm, Piet van Oostrum p...@cs.uu.nl wrote:
  Lacrima lacrima.ma...@gmail.com (L) wrote:
 L Thank you for really useful and detailed explanation. Now I can test
 L my code usingEmacs.
 L But I think it works for me in a little bit different way.
 L My file contains only the print 'hello world'.
 L If I have no python shell running, then:
 L a) C-c RET opens *Python Output* buffer without any output and with
 L 'Shell command succeeded with no output' message at the bottom
 L b) C-c C-c opens *Python Output* with appropriate 'hello world'
 L message.
 L Then I run python shell with C-c ! command. And:
 L a) C-c RET opens *Python* buffer and prints 'hello world' in the
 L python shell
 L b) C-c C-c gives the same result.

 Which version of python-mode.el do you have? (Variable py-version)
 --
 Piet van Oostrum p...@cs.uu.nl
 URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
 Private email: p...@vanoostrum.org

py-version's value is 5.1.0

Also maybe the problem is because I use Emacs version 21.4.1. But I
can't change it to 22, because I access Emacs via SSH on some shared
hosting service.

With regards, Max.
-- 
http://mail.python.org/mailman/listinfo/python-list


Emacs Python-mode. Newbie problem.

2009-07-08 Thread Lacrima
Hello!

I have just started using Emacs to write python scripts.
I installed python-mode.el

Then I just tried this code:

print 'hello world'

When I press C-c RET, new blank window is opened and emacs says:
(Shell command succeeded with no output)
So where is my 'hello world'?

When I do C-c C-c, it prints 'hello world' successfully.
Why in the first case I get no output?

Thanks in advance!

With regards, Max
(sorry if my English isn't very proper)
-- 
http://mail.python.org/mailman/listinfo/python-list


urllib with x509 certs

2009-07-04 Thread Lacrima
Hello!

I am trying to use urllib to fetch some internet resources, using my
client x509 certificate.
I have divided my .p12 file into mykey.key and mycert.cer files.
Then I use following approach:
 import urllib
 url = 'https://example.com'
 xml = '''request
... somexmlsomexml/somexml
/request'''
 opener = urllib.URLopener(key_file = 'mykey.key', cert_file = 'mycert.cer')
 f = opener.open(url, xml)

This works Ok! But every time I am asked to enter PEM pass phrase,
which I specified during dividing my .p12 file.
So my question... What should I do to make my code fetch any url
automatically (without asking me every time to enter pass phrase)?
As I understand there is impossible to specify pass phrase while
constructing URLopener.
So what should I do?

With regards, Max
(sorry if my English isn't very proper)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib with x509 certs

2009-07-04 Thread Lacrima
On Jul 4, 11:24 am, Chris Rebert c...@rebertia.com wrote:
 On Sat, Jul 4, 2009 at 1:12 AM, Lacrimalacrima.ma...@gmail.com wrote:
  Hello!

  I am trying to use urllib to fetch some internet resources, using my
  client x509 certificate.
  I have divided my .p12 file into mykey.key and mycert.cer files.
  Then I use following approach:
  import urllib
  url = 'https://example.com'
  xml = '''request
  ... somexmlsomexml/somexml
  /request'''
  opener = urllib.URLopener(key_file = 'mykey.key', cert_file = 
  'mycert.cer')
  f = opener.open(url, xml)

  This works Ok! But every time I am asked to enter PEM pass phrase,
  which I specified during dividing my .p12 file.
  So my question... What should I do to make my code fetch any url
  automatically (without asking me every time to enter pass phrase)?
  As I understand there is impossible to specify pass phrase while
  constructing URLopener.
  So what should I do?

 Subclass FancyURLopener
 [http://docs.python.org/library/urllib.html#urllib.FancyURLopener],
 overriding the prompt_user_passwd() method
 [http://docs.python.org/library/urllib.html#urllib.FancyURLopener.prom...].
 Then use an instance of your subclass instead of URLopener.

 Cheers,
 Chris
 --http://blog.rebertia.com

Hi Chris,
Thanks for your quick reply.
According to docs the return value of prompt_user_passwd() method
should be a tuple (user, password), but there is no user when
authenticating with certificate. So how should I use this method? This
doesn't work:
 import urllib
 class MyOpener(urllib.FancyURLopener):
...  def prompt_user_passwd(self, host, realm):
...  return ('password')
...


With regards, Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib with x509 certs

2009-07-04 Thread Lacrima
On Jul 4, 12:38 pm, Martin v. Löwis mar...@v.loewis.de wrote:
  This works Ok! But every time I am asked to enter PEM pass phrase,
  which I specified during dividing my .p12 file.
  So my question... What should I do to make my code fetch any url
  automatically (without asking me every time to enter pass phrase)?
  As I understand there is impossible to specify pass phrase while
  constructing URLopener.
  So what should I do?

 You can remove the passphrase on the private key, e.g. with the
 openssl rsa utility.

 Regards,
 Martin

Hi Martin!

Thanks for the reply. I want my key to be as secure as possible. So I
will remove pass phrase if only there is no other possibility to go
through authentication.

With regards, Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What text editor is everyone using for Python

2009-05-26 Thread Lacrima
I am new to python.
And now I am using trial version of Wing IDE.
But nobody mentioned it as a favourite editor.
So should I buy it when trial is expired or there are better choices?
-- 
http://mail.python.org/mailman/listinfo/python-list


Simple question about accessing instance properties.

2009-05-21 Thread Lacrima
Hello!

I think I have a very simple question, but I can't understand how to
access object properties in a way described below.
For example I have an instance of any class:

 class Person:
def __init__(self):
self.name = 'John'
self.email = 'j...@example.com'
self.phone = '3453454'
 person = Person()

Then I have a list of person's properties represented as strings:
 prop_list = ['name', 'email', 'phone']

And my question is how to access person's properties using prop_list?
Do I have to somehow convert 'name', 'email', 'phone'?

With regards,
Max.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple question about accessing instance properties.

2009-05-21 Thread Lacrima
On May 21, 7:04 pm, MRAB goo...@mrabarnett.plus.com wrote:
 Lacrima wrote:
  Hello!

  I think I have a very simple question, but I can't understand how to
  access object properties in a way described below.
  For example I have an instance of any class:

  class Person:
     def __init__(self):
             self.name = 'John'
             self.email = 'j...@example.com'
             self.phone = '3453454'
  person = Person()

  Then I have a list of person's properties represented as strings:
  prop_list = ['name', 'email', 'phone']

  And my question is how to access person's properties using prop_list?
  Do I have to somehow convert 'name', 'email', 'phone'?

   getattr(person, name)
 'John'

Hi!
Thanks a lot!!!
That's so simple!

With regards,
Max.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking for required arguments when instantiating class.

2009-05-07 Thread Lacrima
On May 6, 3:36 pm, Chris Rebert c...@rebertia.com wrote:
 On Wed, May 6, 2009 at 5:24 AM, Piet van Oostrum p...@cs.uu.nl wrote:



  Lacrima lacrima.ma...@gmail.com (L) wrote:

 L Hello!
 L For example I have two classes:

  class First:
 L     def __init__(self, *args, **kwargs):
 L             pass

  class Second:
 L     def __init__(self, somearg, *args, **kwargs):
 L             self.somearg = somearg

 L How can I test that First class takes 1 required argument and Second
 L class takes no required arguments?
 L So that I could instantiate them in a for loop.

  a = [First, Second]
  for cls in a:
 L     instance = cls()

 L Traceback (most recent call last):
 L   File pyshell#22, line 2, in module
 L     instance = cls()
 L TypeError: __init__() takes at least 2 arguments (1 given)

 L Of course, I can do like this:
  for cls in a:
 L     try:
 L             instance = cls()
 L     except TypeError:
 L             instance = cls('hello')

  print instance.somearg
 L hello

 L But what if I have to instantiate any class with 3 or 4 required
 L arguments? How can I do it?

  cls.__init__.im_func.__code__.co_argcount

  This will include self, so it will be 1 in First and 2 in Second.

 AFAICT, that would count non-required arguments too, which isn't
 strictly what the OP requested.

  However this is very dirty trickery and should not be recommended. It
  may also change in future versions and other implementations of Python.

 Very much agreed.

  I think it would be cleaner to put a class attribute in the classes that
  defines how they should be initialized (e.g. just the number of required
  arguments or more specific information) or have a special factory method
  for this use case.

 Seconded. I'd recommend the latter personally, though it's impossible
 to give a definitive answer without more context.

 Cheers,
 Chris
 --http://blog.rebertia.com

Thanks for all of you!

I think I'll try to write a special method for this case and will
report you result.

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


Checking for required arguments when instantiating class.

2009-05-06 Thread Lacrima
Hello!

For example I have two classes:

 class First:
def __init__(self, *args, **kwargs):
pass

 class Second:
def __init__(self, somearg, *args, **kwargs):
self.somearg = somearg

How can I test that First class takes 1 required argument and Second
class takes no required arguments?
So that I could instantiate them in a for loop.

 a = [First, Second]
 for cls in a:
instance = cls()

Traceback (most recent call last):
  File pyshell#22, line 2, in module
instance = cls()
TypeError: __init__() takes at least 2 arguments (1 given)

Of course, I can do like this:
 for cls in a:
try:
instance = cls()
except TypeError:
instance = cls('hello')

 print instance.somearg
hello

But what if I have to instantiate any class with 3 or 4 required
arguments? How can I do it?

With regards,
Max
--
http://mail.python.org/mailman/listinfo/python-list


Re: Checking for required arguments when instantiating class.

2009-05-06 Thread Lacrima
  class First:

         def __init__(self, *args, **kwargs):
                 pass

  class Second:

         def __init__(self, somearg, *args, **kwargs):
                 self.somearg = somearg

 How can I test that First class takes 1 required argument and Second
 class takes no required arguments?


Sorry, I have made a mistake. Of course, Second class takes 1 required
argument, not First.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Restart generator when it is exhausted.

2009-04-29 Thread Lacrima
On Apr 28, 6:38 pm, J. Cliff Dyer j...@sdf.lonestar.org wrote:
 On Tue, 2009-04-28 at 10:41 +, Duncan Booth wrote:
  Lacrima lacrima.ma...@gmail.com wrote:

   If it is not possible what are common techniques to use iterator or
   generator objects that allow restarting when it is needed?

  The usual thing if you want to use the generator's output more than once  
  would be to convert the generator to a list, then you can iterate over it
  as often as you want.

   a = ['a', 'b', 'c']
   g = (i for i in a)
   restartable = list(g)

  If you want the output of the generator to potentially change each time you
  iterate then you need to create a new generator.

 More verbosely, but without putting your generator in , you can use the
 iterator protocol to create a reusable iterable:

 An iterable is a class with an __iter__ method that returns an iterator.

 So for example:

 class Iterator(object):
     def __init__(self, filename):
         self.f = open(filename)

     def __iter__(self):
         return self

     def next(self):
         line = self.f.readline()
         if not line:
             raise StopIteration
         return line.strip()[:8]

 is an iterator (which is also an iterable), which will grab each line of
 a file, returning the first eight non-whitespace characters until the
 file is used up.  Then the iterator is exhausted, and will continue to
 raise StopIteration each time it is called.

 class Iterable(object):
     def __init__(self, filename):
         self.filename = filename

     def __iter__(self):
         return Iterator(self.filename)

 This is a reusable iterable which returns a new instance of the Iterator
 class above each time it is exhausted.

 So given a file hello.txt:

   Hello world
     Hola mundo
   Guten tag, weld.

 The classes can be used as followed: iterator = Iterator('hello.txt')
  for i in xrange(3):
      print *** %d *** % i
      for j in iterator:
          print j

 *** 0 ***
 Hello wo
 Hola mun
 Guten ta
 *** 1 ***
 *** 2 *** iterable = Iterable('hello.txt')
  for i in xrange(3):
      print *** %d *** % i
      for j in iterable:
          print j

 *** 0 ***
 Hello wo
 Hola mun
 Guten ta
 *** 1 ***
 Hello wo
 Hola mun
 Guten ta
 *** 2 ***
 Hello wo
 Hola mun
 Guten ta

 When Iterator hits a StopIteration, it passes out of the inner loop, and
 when it comes back in, the inner loop calls iterator.__iter__(), and
 gets the same exhausted iterator (which immediately breaks the inner
 loop by raising StopIteration).  In Iterable, when the loop calls
 iterable.__iter__(), it gets a fresh iterator, so it can loop over the
 file again.

 The important thing is that when you call x.__iter__() (which you do
 when entering a loop), you get a fresh iterator that won't just call
 StopIteration right away.

 Cheers,
 Cliff

Thank you very much! You completely have enlightened me on all my
questions!

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


Restart generator when it is exhausted.

2009-04-28 Thread Lacrima
Hello!

I am quite new to Python and I have maybe simple (or maybe not)
question.

Is it possible to restart generator when it is exhausted?
For example:
 a = ['a', 'b', 'c']
 g = (i for i in a)
 g.next()
'a'
 g.next()
'b'
 g.next()
'c'
 g.next()
Traceback (most recent call last):
  File pyshell#31, line 1, in module
g.next()
StopIteration

What should I do to get the initial state of g? So if I do again g.next
() I receive 'a'.

If it is not possible what are common techniques to use iterator or
generator objects that allow restarting when it is needed?

With regards,
Max

(sorry if my English isn't very proper)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Restart generator when it is exhausted.

2009-04-28 Thread Lacrima
On Apr 28, 1:04 pm, Chris Rebert c...@rebertia.com wrote:
 On Tue, Apr 28, 2009 at 2:54 AM, Lacrima lacrima.ma...@gmail.com wrote:
  Hello!

  I am quite new to Python and I have maybe simple (or maybe not)
  question.

  Is it possible to restart generator when it is exhausted?

 No. You have to make a new instance of the generator.

  What should I do to get the initial state of g? So if I do again g.next
  () I receive 'a'.

 g = (i for i in a) #that is, make a fresh generator instance

  If it is not possible what are common techniques to use iterator or
  generator objects that allow restarting when it is needed?

 There's itertools.cycle() 
 --http://docs.python.org/library/itertools.html#itertools.cycle

 Cheers,
 Chris
 --http://blog.rebertia.com

Chris, thanks a lot for the help!
--
http://mail.python.org/mailman/listinfo/python-list