Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Discussion options

class Connection():
    ...
    def __enter__(self):
        if not self.open:
            self.ping(reconnect=True)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()
        if exc_val:
            raise
            
            
conn = Connection(...)

#for every request use
with conn, conn.cursor() as cur:
    ... #first request
    
...
time.sleep(many) #many times without requests
...

with conn, conn.cursor() as cur:
    ... #second request

# etc

if db drop the connection, context manager with do a reconnect in __enter__()

You must be logged in to vote

Replies: 1 comment · 3 replies

Comment options

What is the difference from this?

def create_connection():
    return pymysql.connect(...)

with create_connection() as conn:
    # first use

with create_connection() as conn:
    # second use

I don't want to implement "maybe convenient for some people" behaviors. Such behaviors make long-term maintenance cost. Convenient features must be implemented in the higher layer as possible. Low-level library must focus on low-level.

You must be logged in to vote
3 replies
@dashedman
Comment options

So, why you adding implement for "with" without proffit? Just for ignore of exceptions? - it's bad behavior for low-level library :c

@methane
Comment options

So, why you adding implement for "with" without profit?

Have you ever used file objects? Using with for closing file object is best practice. And file objects don't provide "implicit reopen" as you suggested:

f = open(path)

with f:
    d1 = f.read()

with f:  # open again; this is not supported.
    d2 = f.read()

Do you think it is without profit? It's bad behavior?

@dashedman
Comment options

It's not a low-level library)

I undestand you.
In pep 343 -- The "with" Statement(Caching Context Managers), says "Many context managers (such as files and generator-based contexts) will be single-use objects." Many but not all...

I'll close this disscusion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
💡
Ideas
Labels
None yet
2 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.