Re: Best use of "open" context manager

2024-07-12 Thread Albert-Jan Roskam via Python-list
Or like below, although pylint complains about this: "consider using with". Less indentation this way. f = None try: f = open(FILENAME) records = f.readlines() except Exception: sys.exit(1) finally: if f is not None: f.close() -- https://mai

Re: Best use of "open" context manager

2024-07-08 Thread Rob Cliffe via Python-list
On 06/07/2024 12:57, Oscar Benjamin via Python-list wrote: On Sat, 6 Jul 2024 at 11:55, Rob Cliffe via Python-list wrote: Consider this scenario (which I ran into in real life): I want to open a text file and do a lot of processing on the lines of that file. If the file does not e

Re: Best use of "open" context manager

2024-07-07 Thread Cameron Simpson via Python-list
On 07Jul2024 22:22, Rob Cliffe wrote: it's legal, but doesn't work (trying to access the file after "with f" raises the same     ValueError: I/O operation on closed file. Just to this: of course. The with closes the file. But my version runs the with after the try/except. -- https://mail.py

Re: Best use of "open" context manager

2024-07-07 Thread Cameron Simpson via Python-list
On 07Jul2024 22:22, Rob Cliffe wrote: Remember, the `open()` call returns a file object _which can be used as a context manager_. It is separate from the `with` itself. Did you test this?     f = open(FileName) as f: is not legal syntax. No. You're right, remove the "as f:".

Re: Best use of "open" context manager

2024-07-07 Thread Rob Cliffe via Python-list
... process the lines here ... Remember, the `open()` call returns a file object _which can be used as a context manager_. It is separate from the `with` itself. Did you test this?     f = open(FileName) as f: is not legal syntax. If you omit the "as f:" it's legal, but doesn'

Re: Best use of "open" context manager

2024-07-06 Thread Cameron Simpson via Python-list
pen()` call returns a file object _which can be used as a context manager_. It is separate from the `with` itself. -- https://mail.python.org/mailman/listinfo/python-list

Re: Best use of "open" context manager

2024-07-06 Thread dn via Python-list
it like this: try:     f = open(FileName) as f:     FileLines = f.readlines() except FileNotFoundError:     print(f"File {FileName} not found")     sys.exit() # I forgot to put "f.close()" here -:) for ln in File Lines:         print("I do a lot of processing here")   

Re: Best use of "open" context manager

2024-07-06 Thread Richard Damon via Python-list
FoundError:     print(f"File {FileName} not found")     sys.exit() # I forgot to put "f.close()" here -:) for ln in File Lines:         print("I do a lot of processing here")         # Many lines of code here . but this loses the benefits of using "open"

Re: Best use of "open" context manager

2024-07-06 Thread Thomas Passin via Python-list
eName) as f:     FileLines = f.readlines() except FileNotFoundError:     print(f"File {FileName} not found")     sys.exit() # I forgot to put "f.close()" here -:) for ln in File Lines:         print("I do a lot of processing here")         # Many lines of code here ..

Re: Best use of "open" context manager

2024-07-06 Thread Oscar Benjamin via Python-list
On Sat, 6 Jul 2024 at 11:55, Rob Cliffe via Python-list wrote: > > Consider this scenario (which I ran into in real life): > I want to open a text file and do a lot of processing on the lines > of that file. > If the file does not exist I want to take appropriate action, e.g. > print an

Re: Best use of "open" context manager

2024-07-06 Thread Alan Gauld via Python-list
On 06/07/2024 11:49, Rob Cliffe via Python-list wrote: >     If the file does not exist I want to take appropriate action, e.g. > print an error message and abort the program. > I might write it like this: > > try: >     with open(FileName) as f: >         for ln in f: >             print("I

Re: Best use of "open" context manager

2024-07-06 Thread Dan Sommers via Python-list
On 2024-07-06 at 11:49:06 +0100, Rob Cliffe via Python-list wrote: > Is there a better / more Pythonic solution? https://docs.python.org/3/library/fileinput.html At least this attempts to abstract the problem of iterating over a file (or multiple files) into a library routine. I've used it a l

Best use of "open" context manager

2024-07-06 Thread Rob Cliffe via Python-list
tFoundError:     print(f"File {FileName} not found")     sys.exit() # I forgot to put "f.close()" here -:) for ln in File Lines:         print("I do a lot of processing here")         # Many lines of code here . but this loses the benefits of using "open" as a cont

Re: Suggested python feature: allowing except in context maneger

2024-06-17 Thread j via Python-list
On 2024-06-13 23:49, Cameron Simpson via Python-list wrote: On 13Jun2024 19:44, dieter.mau...@online.de wrote: Why not use: ``` try:  with open()...    ... except FileNotFoundError:  ... ``` This is exactly what the OP was expressing dissatisfaction with. I'm -1 on the idea myself - not eve

Re: Suggested python feature: allowing except in context maneger

2024-06-16 Thread Albert-Jan Roskam via Python-list
The example exception is not what bothers me. The syntax change is nowhere near as useful as `with` and context managers. They provide an excellent idiom for resource usage and release. Your suggestion complicates the `with` statement and brings only a tiny indentation

Re: Suggested python feature: allowing except in context maneger

2024-06-14 Thread Cameron Simpson via Python-list
On 14Jun2024 09:07, Yair Eshel wrote: Cameron, I'm not really sure I got your point. I've used the "file not found" exception as an example for a behavior typical on context managers. This could be a failure to connect to DB, or threads. It also applies to any kind o

Re: Suggested python feature: allowing except in context maneger

2024-06-13 Thread Yair Eshel via Python-list
Cameron, I'm not really sure I got your point. I've used the "file not found" exception as an example for a behavior typical on context managers. This could be a failure to connect to DB, or threads. It also applies to any kind of possible exception, whether cased by the conte

Re: Suggested python feature: allowing except in context maneger

2024-06-13 Thread Cameron Simpson via Python-list
On 13Jun2024 19:44, dieter.mau...@online.de wrote: Why not use: ``` try: with open()... ... except FileNotFoundError: ... ``` This is exactly what the OP was expressing dissatisfaction with. I'm -1 on the idea myself - not every combination of things needs additional syntactic support,

Suggested python feature: allowing except in context maneger

2024-06-13 Thread Dieter Maurer via Python-list
> logging.error("File not") Are you aware that in the case of a `FileNotFoundError` no context manager is created (the context manager is the `f` in your code). Why not use: try: with open()... ... except FileNotFoundError: ... I do not think that your use case requ

Re: Suggested python feature: allowing except in context maneger

2024-06-13 Thread Barry Scott via Python-list
> On 13 Jun 2024, at 11:01, Yair Eshel via Python-list > wrote: > > I read this is a good place to give some suggestions for features in > python. Best place these days is to raise an idea on https://discuss.python.org/ Beware that this idea has come up in the past and was rejected. Barry

Suggested python feature: allowing except in context maneger

2024-06-13 Thread Yair Eshel via Python-list
FoundError: logging.error("File not found") As you can see I have 2 levels of indentation, which can add some pain to the work with the context manager. This code without context manager, can be replaced by this code: import logging try: f = open('sample_data/READM.md') as f:

RE: Context without manager

2023-11-27 Thread David Raymond via Python-list
> I *must* do: > > with device_open() as device: >device.do_something() > > Nevertheless, I _need_ to have a class > where the device is opened in the __init__() > and used in some methods. > > Any ideas? Perhaps take a look at contextlib.ExitStack and see if you can do something with it.

Context without manager

2023-11-27 Thread Richard Damon via Python-list
Read the Fine context manager documentation. What “with with_expression as var” does is effectively: ob = with_expression var = ob.__enter__() And then at the end of the with, does a ob.__exit__() (With some parameters to __exit__, that could just be None, None, None for the simplest case

Re: Context without manager

2023-11-27 Thread Richard Damon via Python-list
Read the Fine context manager documentation. What “with with_expression as var” does is effectively: ob = with_expression var = ob.__enter__() And then at the end of the with, does a ob.__exit__() (With some parameters to __exit__, that could just be None, None, None for the simplest case

Re: Context without manager

2023-11-27 Thread Piergiorgio Sartor via Python-list
On 26/11/2023 18.50, Dieter Maurer wrote: Piergiorgio Sartor wrote at 2023-11-25 22:15 +0100: ... Apparently, the "with" context manager is not usable in classes, at least not with __init__() & co. You can use `with` in classes -- with any context manager. However, you would u

Re: Context without manager

2023-11-26 Thread Greg Ewing via Python-list
On 27/11/23 5:03 pm, Grant Edwards wrote: I should probably have written "how to fool that into working when he's not using a 'with' statement" It should be possible to run the context protocol yourself. Something like (warning, untested): class MyDeviceWrapp

Re: Context without manager

2023-11-26 Thread Greg Ewing via Python-list
On 27/11/23 9:03 am, Stefan Ram wrote: Above, "have" is followed by another verb in "have been", so it should be eligible for a contraction there! Yes, "been" is the past participle of 'to be", so "I've been" is fine. -- Greg -- https://mail.python.org/mailman/listinfo/python-list

Re: Context without manager

2023-11-26 Thread Grant Edwards via Python-list
On 2023-11-27, Grant Edwards via Python-list wrote: > On 2023-11-26, Dieter Maurer via Python-list wrote: > >> If you do not have this case (e.g. usually if you open the file >> in a class's `__init__`), you do not use a context manager. > > He knows that. The OP wro

Re: Context without manager

2023-11-26 Thread Grant Edwards via Python-list
On 2023-11-26, Dieter Maurer via Python-list wrote: > If you do not have this case (e.g. usually if you open the file > in a class's `__init__`), you do not use a context manager. He knows that. The OP wrote that he wants to use that can _only_ be used by a context manager, but he

Re: Context without manager

2023-11-26 Thread Dieter Maurer via Python-list
Piergiorgio Sartor wrote at 2023-11-25 22:15 +0100: > ... >Apparently, the "with" context manager is not usable >in classes, at least not with __init__() & co. You can use `with` in classes -- with any context manager. However, you would usually not use `with` with a

Context without manager

2023-11-26 Thread Piergiorgio Sartor via Python-list
Hi all, I apologize in advance for the "foggy" question, but I've myself unclear ideas. Anyway... Python has "context manager". For example, the "open()" class can be simply used as follow: with open(...) as fp: fp.do_something() On the other hand, it

Re: Context manager for database connection

2023-08-23 Thread dn via Python-list
]) -> bool: if exception_type: self.database_connection.rollback() else: self.database_connection.commit() self.database_connection.close() def get_connection(self) -> jdbc.Connection: return self.database_connection Using a context-manag

Re: Context manager for database connection

2023-08-23 Thread dn via Python-list
se_connection.close() def get_connection(self) -> jdbc.Connection: return self.database_connection Looking good! Assuming this is the only DB-interaction, a context-manager seems appropriate. If the real use-case calls for more interactions, the cost of establishing and

Context manager for database connection

2023-08-23 Thread Jason Friedman via Python-list
I want to be able to write code like this: with Database() as mydb: conn = mydb.get_connection() cursor = conn.get_cursor() cursor.execute("update table1 set x = 1 where y = 2") cursor.close() cursor = conn.get_cursor() cursor.execute("update table2 set a = 1 where b = 2") cursor.close() I'd like

Re: ContextVars in async context

2022-12-21 Thread Dieter Maurer
Marce Coll wrote at 2022-12-20 22:09 +0100: >Hi python people, hope this is the correct place to ask this! > >For a transactional async decorator I'm building I am using contextvars in >order to know when a transaction is open in my current context. > >My understandi

ContextVars in async context

2022-12-20 Thread Marce Coll
Hi python people, hope this is the correct place to ask this! For a transactional async decorator I'm building I am using contextvars in order to know when a transaction is open in my current context. My understanding is that if given the following call stack A |- B | |- C |- D |-

Re: Unable to find 'edit with ide' option in the Context menu

2021-03-31 Thread Terry Reedy
On 3/31/2021 2:11 AM, Arjav Jain wrote: I am using the lastest version of python recently. But I am facing a problem with the python files, When I am right clicking any python file there is no option for `Edit with idle'. I have repaired the python installation too, but this doesn

Unable to find 'edit with ide' option in the Context menu

2021-03-31 Thread Arjav Jain
I am using the lastest version of python recently. But I am facing a problem with the python files, When I am right clicking any python file there is no option for `Edit with idle'. I have repaired the python installation too, but this doesn't solves my problem, please help! Sent f

Re: print() ignores context ?

2020-05-05 Thread Greg Ewing
On 1/05/20 8:33 pm, R.Wieser wrote: getcontext().rounding=ROUND_HALF_UP print(round(1.5)) print(round(2.5)) If you're talking about getcontext() from the decimal module, that only affects operations with Decimals, not regular floats. Python doesn't provide a way to change the rounding mode fo

Re: What is a backing store in the context of module io https://docs.python.org/3/library/io.html

2019-11-11 Thread Terry Reedy
On 11/11/2019 11:08 AM, Veek M wrote: https://docs.python.org/3/library/io.html 'Text I/O expects and produces str objects. This means that whenever the backing store is natively made of bytes (such as in the case of a file), encoding and decoding of data is made transparently as well as optiona

Re: What is a backing store in the context of module io https://docs.python.org/3/library/io.html

2019-11-11 Thread Peter Otten
Veek M wrote: > I was reading pydoc io and - how do I decipher the indentation? $ cat demo.py class Base: pass class Sub(Base): pass class SubSub(Sub): pass class Other: pass class OtherSub(Other, Base): pass $ pydoc3.7 demo | head -n13 Help on module demo: NAME demo CLASSES builtins.o

Re: What is a backing store in the context of module io https://docs.python.org/3/library/io.html

2019-11-11 Thread Veek M
On Mon, 11 Nov 2019 16:08:12 +, Veek M wrote: > So i was making some notes and: https://i.imgur.com/UATAKXh.png > > I did not understand this > > https://docs.python.org/3/library/io.html 'Text I/O expects and produces > str objects. This means that whenever the backing store is natively mad

What is a backing store in the context of module io https://docs.python.org/3/library/io.html

2019-11-11 Thread Veek M
So i was making some notes and: https://i.imgur.com/UATAKXh.png I did not understand this https://docs.python.org/3/library/io.html 'Text I/O expects and produces str objects. This means that whenever the backing store is natively made of bytes (such as in the case of a file), encoding and dec

Async subprocess context manager

2019-09-01 Thread Peter Sutton
Hi all, First time posting! I need an async context manager that ensures a Process has finished before it `__exit__()`s, either by graceful or forceful termination, and regardless of cancellation. I've put my code at the bottom. I'm relatively new to asyncio, so I'm looking for

Re: Feature suggestion: "Using declarations" i.e. context managers ("with" blocks) tied to scope/lifetime of the variable rather than to nesting

2019-02-21 Thread Thomas Jollans
On 21/02/2019 19:35, mnl.p...@gmail.com wrote: > (I sent this a few days ago but got bounced without a reason—don’t see it > posted, so I’m trying one more time.) No, it got through. And it's in the archive: https://mail.python.org/pipermail/python-list/2019-February/739548.html -- https://mail

Re: Feature suggestion: "Using declarations" i.e. context managers ("with" blocks) tied to scope/lifetime of the variable rather than to nesting

2019-02-21 Thread Rhodri James
https://mail.python.org/pipermail/python-list/2019-February/739548.html I thought this new C# feature would be a good thing to add to Python: https://vcsjones.com/2019/01/30/csharp-8-using-declarations/ The nesting required by context managers can be at odds with a program’s real structure. Really? I thoug

Feature suggestion: "Using declarations" i.e. context managers ("with" blocks) tied to scope/lifetime of the variable rather than to nesting

2019-02-21 Thread mnl.p...@gmail.com
(I sent this a few days ago but got bounced without a reason—don’t see it posted, so I’m trying one more time.) I thought this new C# feature would be a good thing to add to Python: https://vcsjones.com/2019/01/30/csharp-8-using-declarations/ The nesting required by context managers can be at

Re: Feature suggestions: "Using declarations" i.e. context managers ("with" blocks) tied to scope/lifetime of the variable rather than to nesting

2019-02-19 Thread Ben Finney
"mnl.p...@gmail.com" writes: > with xx.open() as logfile: > do this > do that > logfile.write() > do this > do that > logfile.write() That's a good sign you have identified a discrete collection of statements that should be in a function. The function accepts ‘l

Re: Feature suggestions: "Using declarations" i.e. context managers ("with" blocks) tied to scope/lifetime of the variable rather than to nesting

2019-02-19 Thread Thomas Jollans
On 19/02/2019 05.15, mnl.p...@gmail.com wrote: > This becomes more ugly if multiple withs get nested. > This is what contextlib.ExitStack is for. -- https://mail.python.org/mailman/listinfo/python-list

Re: Feature suggestions: "Using declarations" i.e. context managers ("with" blocks) tied to scope/lifetime of the variable rather than to nesting

2019-02-19 Thread Neil Cerutti
On 2019-02-19, mnl.p...@gmail.com wrote: > I thought this new C# feature would be a good thing to add to Python: > https://vcsjones.com/2019/01/30/csharp-8-using-declarations/ > > I find the nesting required by context managers to be at odds with the > broad intent. > > Th

Re: Feature suggestions: "Using declarations" i.e. context managers ("with" blocks) tied to scope/lifetime of the variable rather than to nesting

2019-02-19 Thread Rhodri James
This is probably better discussed on python-ideas, but here goes: On 19/02/2019 04:15, mnl.p...@gmail.com wrote: I thought this new C# feature would be a good thing to add to Python: https://vcsjones.com/2019/01/30/csharp-8-using-declarations/ I find the nesting required by context managers to

Feature suggestions: "Using declarations" i.e. context managers ("with" blocks) tied to scope/lifetime of the variable rather than to nesting

2019-02-19 Thread mnl.p...@gmail.com
I thought this new C# feature would be a good thing to add to Python: https://vcsjones.com/2019/01/30/csharp-8-using-declarations/ I find the nesting required by context managers to be at odds with the broad intent. The code indentation in python should reflect the program logic and flow as much

Re: Context manager on method call from class

2018-03-15 Thread Joseph L. Casale
From: Python-list on behalf of Rob Gaddi Sent: Thursday, March 15, 2018 12:47 PM To: python-list@python.org Subject: Re: Context manager on method call from class   > from contextlib import contextmanager. > > Then you just use the @contextmanager decorator on a function, have it

Re: Context manager on method call from class

2018-03-15 Thread Rob Gaddi
On 03/15/2018 11:17 AM, Joseph L. Casale wrote: I have a class which implements a context manager, its __init__ has a signature and the __enter__ returns an instance of the class. Along with several methods which implement functionality on the instance, I have one method which itself must open

Context manager on method call from class

2018-03-15 Thread Joseph L. Casale
I have a class which implements a context manager, its __init__ has a signature and the __enter__ returns an instance of the class. Along with several methods which implement functionality on the instance, I have one method which itself must open a context manager against a call on an instance

Re: Re: Context manager able to write to the caller's namespace

2018-01-18 Thread Chris Angelico
On Fri, Jan 19, 2018 at 5:00 PM, wrote: > Hello, > > Thank you for your mail. I will answer as fast as possible. If you're going to subscribe to a mailing list, PLEASE disable your autoresponder. Otherwise, messages like this will get marked as Spam, and your legit mail will end up getting tarr

Re: Context manager able to write to the caller's namespace

2018-01-18 Thread Steven D'Aprano
On Fri, 19 Jan 2018 16:49:49 +1100, Chris Angelico wrote: [...] > 1) Context manager was called from global scope, and needs access to > globals() or locals() as returned in the caller A! /facepalm Of course the caller can just pass locals() to the context manager. Why didn

Re: Context manager able to write to the caller's namespace

2018-01-18 Thread Chris Angelico
On Fri, Jan 19, 2018 at 3:48 PM, Steven D'Aprano wrote: > I want to define a context manager in one module: > > # a.py > def CM: > def __enter__(self): > return self > def __exit__(self, *args): > pass > > > Then call it from anothe

Context manager able to write to the caller's namespace

2018-01-18 Thread Steven D'Aprano
I'm looking for a solution, or at least hints, to this problem. I want to define a context manager in one module: # a.py def CM: def __enter__(self): return self def __exit__(self, *args): pass Then call it from another module: # b.py import a with a.CM() as

Re: Redirecting stdio streams with a context manager

2017-09-29 Thread Thomas Jollans
irect_stdout(f2) with redir_file1: # do stuff with redir_file2: # Other stuff # Oh no wait actually with redir_file1: # Dum dee dum dee dum pass > > If you use the context manager twice: > > with redirect_stdout(f1) as instance1: > with

Re: Redirecting stdio streams with a context manager

2017-09-29 Thread Peter Otten
moved > _stream = "stdout" > > class redirect_stderr(_RedirectStream): > # docstring removed > _stream = "stderr" > > > > I don't understand the comment "We use a list of old targets to make this > CM re-entrant". Under what circums

Redirecting stdio streams with a context manager

2017-09-29 Thread Steve D'Aprano
't understand the comment "We use a list of old targets to make this CM re-entrant". Under what circumstances will there ever be more than a single entry in _old_targets? If you use the context manager twice: with redirect_stdout(f1) as instance1: with redirect_stdout(f2) as ins

exception_guard context manager and decorator

2017-06-25 Thread Steve D'Aprano
As discussed in the Python-Ideas mailing list, sometimes we want to suppress a particular kind of exception and replace it with another. For that reason, I'd like to announce exception_guard, a context manager and decorator which catches specified exceptions and replaces them with a

Re: Fw: Context

2017-02-03 Thread Terry Reedy
On 2/3/2017 8:10 AM, Antonio wrote: I have python version 3.6.0 installed into my desktop)windows 7) but the menu/context (file,edit..etc) is missing. Run IDLE (there should be a Start menu icon) or install or run another IDE. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo

Re: Context

2017-02-03 Thread William Ray Wing
> On Feb 3, 2017, at 8:10 AM, Antonio wrote: > > From: Antonio > Sent: Friday, February 3, 2017 1:02 PM > To: python-list@python.org > Subject: Context > > I have python version 3.6.0 installed into my desktop)windows 7) but the > m

Fw: Context

2017-02-03 Thread Antonio
From: Antonio Sent: Friday, February 3, 2017 1:02 PM To: python-list@python.org Subject: Context I have python version 3.6.0 installed into my desktop)windows 7) but the menu/context (file,edit..etc) is missing. How to fix this problem? Thanks Antonio

Re: Error handling in context managers

2017-01-17 Thread Israel Brewster
On Jan 16, 2017, at 11:34 PM, Peter Otten <__pete...@web.de> wrote: > > Gregory Ewing wrote: > >> Israel Brewster wrote: >>> The problem is that, from time to time, I can't get a connection, the >>> result being that cursor is None, >> >> That's your problem right there -- you want a better-beha

Re: Error handling in context managers

2017-01-17 Thread Israel Brewster
On Jan 16, 2017, at 8:01 PM, Gregory Ewing wrote: > > Israel Brewster wrote: >> The problem is that, from time to time, I can't get a connection, the result >> being that cursor is None, > > That's your problem right there -- you want a better-behaved > version of psql_cursor(). > > def get_psq

Re: Error handling in context managers

2017-01-17 Thread Israel Brewster
On Jan 16, 2017, at 1:27 PM, Terry Reedy wrote: > > On 1/16/2017 1:06 PM, Israel Brewster wrote: >> I generally use context managers for my SQL database connections, so I can >> just write code like: >> >> with psql_cursor() as cursor: >> >> >&

Re: Error handling in context managers

2017-01-17 Thread Peter Otten
Gregory Ewing wrote: > Israel Brewster wrote: >> The problem is that, from time to time, I can't get a connection, the >> result being that cursor is None, > > That's your problem right there -- you want a better-behaved > version of psql_cursor(). > > def get_psql_cursor(): > c = psql_curso

Re: Error handling in context managers

2017-01-16 Thread Gregory Ewing
Terry Reedy wrote: Traceback (most recent call last): File "", line 1, in with None: pass AttributeError: __enter__ Like he said, you get an AttributeError! -- Greg -- https://mail.python.org/mailman/listinfo/python-list

Re: Error handling in context managers

2017-01-16 Thread Gregory Ewing
Israel Brewster wrote: The problem is that, from time to time, I can't get a connection, the result being that cursor is None, That's your problem right there -- you want a better-behaved version of psql_cursor(). def get_psql_cursor(): c = psql_cursor() if c is None: raise CantGet

Re: Error handling in context managers

2017-01-16 Thread Terry Reedy
On 1/16/2017 1:06 PM, Israel Brewster wrote: I generally use context managers for my SQL database connections, so I can just write code like: with psql_cursor() as cursor: And the context manager takes care of making a connection (or getting a connection from a pool, more likely), and

Re: Error handling in context managers

2017-01-16 Thread Marko Rauhamaa
Steve D'Aprano : > or you can let the context manager do what it does, and write your own code > to do what you do: > > try: > with ...: >... > except: > ... Even better: try: a = open(...) except ...: ... with a:

Re: Error handling in context managers

2017-01-16 Thread Steve D'Aprano
On Tue, 17 Jan 2017 05:06 am, Israel Brewster wrote: > I generally use context managers for my SQL database connections, so I can > just write code like: > > with psql_cursor() as cursor: > > > And the context manager takes care of making a connection (or getting a >

Re: Error handling in context managers

2017-01-16 Thread Peter Otten
Israel Brewster wrote: > I generally use context managers for my SQL database connections, so I can > just write code like: > > with psql_cursor() as cursor: > > > And the context manager takes care of making a connection (or getting a > connection from a pool, mo

Re: Error handling in context managers

2017-01-16 Thread Chris Angelico
On Tue, Jan 17, 2017 at 5:06 AM, Israel Brewster wrote: > I generally use context managers for my SQL database connections, so I can > just write code like: > > with psql_cursor() as cursor: > > > And the context manager takes care of making a connection (or getting a

Error handling in context managers

2017-01-16 Thread Israel Brewster
I generally use context managers for my SQL database connections, so I can just write code like: with psql_cursor() as cursor: And the context manager takes care of making a connection (or getting a connection from a pool, more likely), and cleaning up after the fact (such as putting the

Re: ctypes, memory mapped files and context manager

2016-12-30 Thread Peter Otten
eryk sun wrote: > On Thu, Dec 29, 2016 at 12:18 PM, Hans-Peter Jansen wrote: >>> >>> import weakref, ctypes >>> >>> T = ctypes.c_ubyte * 3 >>> >>> t = T() >>> >>> bytes(t) == b"\0" * 3 >>> >>> True >>> >>> >>> bytes(weakref.proxy(t)) == b"\0" * 3 >>> >>> Traceback (most recent call last): >>> F

Re: ctypes, memory mapped files and context manager

2016-12-29 Thread Hans-Peter Jansen
gt;> > >> True > > > > I found a couple of other rough corners already, when working with the > > ctypes module. Obviously, this module is lacking some love. > > That's not the fault of ctypes. There's no requirement for objects > that implem

Re: ctypes, memory mapped files and context manager

2016-12-29 Thread eryk sun
On Thu, Dec 29, 2016 at 12:18 PM, Hans-Peter Jansen wrote: >> >>> import weakref, ctypes >> >>> T = ctypes.c_ubyte * 3 >> >>> t = T() >> >>> bytes(t) == b"\0" * 3 >> >> True >> >> >>> bytes(weakref.proxy(t)) == b"\0" * 3 >> >> Traceback (most recent call last): >> File "", line 1, in >> Attribu

Re: ctypes, memory mapped files and context manager

2016-12-29 Thread Hans-Peter Jansen
On Donnerstag, 29. Dezember 2016 09:33:59 Peter Otten wrote: > Hans-Peter Jansen wrote: > > On Mittwoch, 28. Dezember 2016 16:53:53 Hans-Peter Jansen wrote: > > The minimal example is > > >>> import weakref, ctypes > >>> T = ctypes.c_ubyte * 3 > >>> t = T() > >>> bytes(t) == b"\0" * 3 > > True >

Re: ctypes, memory mapped files and context manager

2016-12-29 Thread Peter Otten
Hans-Peter Jansen wrote: > On Mittwoch, 28. Dezember 2016 16:53:53 Hans-Peter Jansen wrote: >> On Mittwoch, 28. Dezember 2016 15:17:22 Hans-Peter Jansen wrote: >> > On Mittwoch, 28. Dezember 2016 13:48:48 Peter Otten wrote: >> > > Hans-Peter Jansen wrote: >> > > > Dear Peter, >> > > > >> > > > th

Re: ctypes, memory mapped files and context manager

2016-12-28 Thread Hans-Peter Jansen
On Mittwoch, 28. Dezember 2016 16:53:53 Hans-Peter Jansen wrote: > On Mittwoch, 28. Dezember 2016 15:17:22 Hans-Peter Jansen wrote: > > On Mittwoch, 28. Dezember 2016 13:48:48 Peter Otten wrote: > > > Hans-Peter Jansen wrote: > > > > Dear Peter, > > > > > > > > thanks for taking valuable time to l

Re: ctypes, memory mapped files and context manager

2016-12-28 Thread Hans-Peter Jansen
On Mittwoch, 28. Dezember 2016 21:58:38 Peter Otten wrote: > Hans-Peter Jansen wrote: > > On Mittwoch, 28. Dezember 2016 13:48:48 Peter Otten wrote: > >> Hans-Peter Jansen wrote: > > It leaves the question on why is Python2 acting as one would expect > > related to

Re: ctypes, memory mapped files and context manager

2016-12-28 Thread Peter Otten
; > It might be related to my distinct silliness, but the problem persists >> > with your code as well. >> >> Unfortunately I posted the broken toy example rather than the fixed one. >> Here's the latter. Basically you have to keep a reference in the context >

Re: ctypes, memory mapped files and context manager

2016-12-28 Thread Hans-Peter Jansen
; You're welcome! > > > > > It might be related to my distinct silliness, but the problem persists > > > with your code as well. > > > > Unfortunately I posted the broken toy example rather than the fixed one. > > Here's the latter. Basical

Re: ctypes, memory mapped files and context manager

2016-12-28 Thread Hans-Peter Jansen
oblem persists > > with your code as well. > > Unfortunately I posted the broken toy example rather than the fixed one. > Here's the latter. Basically you have to keep a reference in the context > manager (whether you implement it as a class or a generator doesn't matte

Re: ctypes, memory mapped files and context manager

2016-12-28 Thread Peter Otten
r than the fixed one. Here's the latter. Basically you have to keep a reference in the context manager (whether you implement it as a class or a generator doesn't matter) without giving another reference away to client code: $ cat mmap_after.py import ctypes import mmap import weakref from co

Re: ctypes, memory mapped files and context manager

2016-12-28 Thread Hans-Peter Jansen
ove the del statement the > line below will still decrease the refcount. > > Make sure you understand this to avoid littering your code with cargo cult > del-s ;) Yes, I was aware of this. It was a testing relic, that survived somehow. Sorry. Yes, I usually try to avoid cargo

Re: ctypes, memory mapped files and context manager

2016-12-27 Thread Peter Otten
and closable (due to the nature > of mmaps and Python's posix implementation thereof). Hence, a context > manager serves us well (in theory). > > Here's some code excerpt: > > class cstructmap: > def __init__(self, cstruct, mm, offset = 0): > self._cstruct

ctypes, memory mapped files and context manager

2016-12-27 Thread Hans-Peter Jansen
of). Hence, a context manager serves us well (in theory). Here's some code excerpt: class cstructmap: def __init__(self, cstruct, mm, offset = 0): self._cstruct = cstruct self._mm = mm self._offset = offset self._csinst = None def __enter__(self):

Re: context managers inline?

2016-03-11 Thread jmp
On 03/10/2016 07:59 PM, Neal Becker wrote: sohcahto...@gmail.com wrote: On Thursday, March 10, 2016 at 10:33:47 AM UTC-8, Neal Becker wrote: Is there a way to ensure resource cleanup with a construct such as: x = load (open ('my file', 'rb)) Is there a way to ensure this file gets closed?

Re: context managers inline?

2016-03-11 Thread Jussi Piitulainen
Paul Rubin writes: > Jussi Piitulainen writes: >> return ModeIO(f.read()) > > These suggestions involving f.read() assume the file contents are small > enough to reasonably slurp into memory. That's unlike the original > where "load" receives a stream and might process it piecewise. If y

Re: context managers inline?

2016-03-10 Thread Paul Rubin
Jussi Piitulainen writes: > return ModeIO(f.read()) These suggestions involving f.read() assume the file contents are small enough to reasonably slurp into memory. That's unlike the original where "load" receives a stream and might process it piecewise. -- https://mail.python.org/mailma

Re: context managers inline?

2016-03-10 Thread Jussi Piitulainen
Chris Angelico writes: > On Fri, Mar 11, 2016 at 5:33 AM, Neal Becker wrote: >> Is there a way to ensure resource cleanup with a construct such as: >> >> x = load (open ('my file', 'rb)) >> >> Is there a way to ensure this file gets closed? > > Yep! > > def read_file(fn, *a, **kw): > with ope

Re: context managers inline?

2016-03-10 Thread Steven D'Aprano
On Fri, 11 Mar 2016 05:33 am, Neal Becker wrote: > Is there a way to ensure resource cleanup with a construct such as: > > x = load (open ('my file', 'rb)) > > Is there a way to ensure this file gets closed? Depends on what you mean by "ensure". Have load() call the file's close method may be g

Re: context managers inline?

2016-03-10 Thread Chris Angelico
e to your load() function, and have the context manager in there. If you don't do it one of those ways, the question is: WHEN should the file be closed? How does Python know when it should go and clean that up? There's no "end of current expression" rule as there is in C++, so

Re: context managers inline?

2016-03-10 Thread Mark Lawrence
On 10/03/2016 18:33, Neal Becker wrote: Is there a way to ensure resource cleanup with a construct such as: x = load (open ('my file', 'rb)) Is there a way to ensure this file gets closed? I don't see how there can be. Surely you must split it into two lines to use the

Re: context managers inline?

2016-03-10 Thread Ian Kelly
On Thu, Mar 10, 2016 at 11:59 AM, Neal Becker wrote: > sohcahto...@gmail.com wrote: > >> On Thursday, March 10, 2016 at 10:33:47 AM UTC-8, Neal Becker wrote: >>> Is there a way to ensure resource cleanup with a construct such as: >>> >>> x = load (open ('my file', 'rb)) >>> >>> Is there a way to e

  1   2   3   4   5   >