Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With statement in python is returning None object even though __init__ method works

For a DB class with the following init method:

class DB:
    def __init__(self, dbprops):
        self.dbprops = dbprops
        self.conn = self.get_connection(self.dbprops)
        debug("self.conn is %s" %self.conn)

    def __enter__(self):
        pass
    def __exit__(self, exc_type, exc_val, exc_tb):
        if not self.conn is None:
            self.close()

And for a client method invoking it as follows:

with DB(self.dbprops) as db:
    if not db:
        raise Exception("Db is None inside with")
    return db.get_cmdline_sql()

The output shows the debug message - thus the init method was successfully called:

  File "./classifier_wf.py", line 28, in get_cmdline_mysql
      raise Exception("Db is None inside with")

Exception: Db is None inside with

Update: fixed the enter method to return a DB object . But need help on how to invoke it:

  def __enter__(self, dbprops):
    return DB(dbprops)

Invoking it with a single parameter does not work apparently:

 with DB(dbprops) as db:

TypeError: __enter__() takes exactly 2 arguments (1 given)

Now I do not follow because the "self" is supposed to be filled in automatically..

like image 484
WestCoastProjects Avatar asked May 20 '13 22:05

WestCoastProjects


People also ask

Can you return in __ init __?

__init__ is required to return None. You cannot (or at least shouldn't) return something else. Try making whatever you want to return an instance variable (or function).

What does it mean if Python returns None?

The function returns None when the denominator is 0. This makes sense as the result is undefined so sending None sounds natural. However, the user of the function can incorrectly use it as shown below. When the numerator is 0, the function would return 0, which is expected but look at what happens in the if statement.

Can Init method in Python return value?

__init__ method returns a value The __init__ method of a class is used to initialize new objects, not create them. As such, it should not return any value. Returning None is correct in the sense that no runtime error will occur, but it suggests that the returned value is meaningful, which it is not.

What is __ init __ -> None?

def __init__(self, n) -> None: means that __init__ should always return NoneType and it can be quite helpful if you accidentally return something different from None especially if you use mypy or other similar things.


1 Answers

The context manager protocol is handled by the __enter__() and __exit__() methods; the former must return the value to assign.

like image 63
Ignacio Vazquez-Abrams Avatar answered Sep 18 '22 16:09

Ignacio Vazquez-Abrams