[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Need help with "with-statement-compatible" object

Dmitry Teslenko

12/19/2007 8:02:00 AM

Hello!
I've made some class that can be used with "with statement". It looks this way:

class chdir_to_file( object ):
....
def __enter__(self):
....

def __exit__(self, type, val, tb):
....
def get_chdir_to_file(file_path):
return chdir_to_file(file_path)
....

Snippet with object instantiation looks like this:
for s in sys.argv[1:]:
c = chdir_to_file( s )
with c:
print 'Current directory is %s' % os.path.realpath( os.curdir )

That works fine. I want to enable it to be used in more elegant way:
for s in ... :
with get_chdir_to_file( s ) as c:
c.do_something()

But python complains c is of NoneType and has no "do_something()". Am
I missing something?
2 Answers

Peter Otten

12/19/2007 9:15:00 AM

0

Dmitry Teslenko wrote:

> Hello!
> I've made some class that can be used with "with statement". It looks this way:
>
> class chdir_to_file( object ):
> ...
> def __enter__(self):
> ...
>
> def __exit__(self, type, val, tb):
> ...
> def get_chdir_to_file(file_path):
> return chdir_to_file(file_path)
> ...
>
> Snippet with object instantiation looks like this:
> for s in sys.argv[1:]:
> c = chdir_to_file( s )
> with c:
> print 'Current directory is %s' % os.path.realpath( os.curdir )
>
> That works fine. I want to enable it to be used in more elegant way:
> for s in ... :
> with get_chdir_to_file( s ) as c:
> c.do_something()
>
> But python complains c is of NoneType and has no "do_something()". Am
> I missing something?

Does the chdir_to_file class have a do_something() method? If so,
changing chdir_to_file.__enter__() to

def __enter__(self):
# ...
return self

should help.

Peter

Dmitry Teslenko

12/19/2007 10:48:00 AM

0

On Dec 19, 2007 12:14 PM, Peter Otten <__peter__@web.de> wrote:
> def __enter__(self):
> # ...
> return self
>
> should help.

That helps. Thanks!