Python3 - How do I import a class from another file

Roel Schroeven roel at roelschroeven.net
Wed Dec 11 15:44:57 EST 2019


R.Wieser schreef op 11/12/2019 om 11:43:> MRAB,
 >
 >>  From the help:
 > ...
 >> Do not depend on immediate finalization of objects when they become
 >> unreachable (so you should always close files explicitly).
 >
 > Do you notice there is not a single word about (the delayed action 
of) the
 > __del__ method in there ?  Why than do you think its talking about it ?
Hm wait. You're not mixing up del and __del__() here, do you? Calling 
del does not directly lead to __del__() being called. See 
https://docs.python.org/3/reference/datamodel.html?highlight=__del__#object.__del__

"Note: del x doesn’t directly call x.__del__() — the former decrements 
the reference count for x by one, and the latter is only called when x’s 
reference count reaches zero."
 > You know how I read that ?   As if its talking about /variables going 
outof
 > scope/.   Makes sense ?    Thought so.  :-)
Not only going out of scope. Deleting references using del does the same 
thing.
 > Hmmm...  Maybe the __del__ method was created exactly to solve this late
 > handling of going-outof-scope variables.  What do you think ?
__del__ is not directly related to variables going out of scope, just as 
it is not directly related to the del statement. Going out of scope and 
del have one and only one direct effect: the reference count goes down. 
Once the reference count is zero, the object can be garbage collected. 
That is when __del__() is called.


 > And by the way: /when/ would you close those files explicitily ?
When you're done with them.

def count_lines(filename):
     f = open(filename, 'r')
     try:
         return sum(1 for line in f)
     finally:
         f.close()

Or better with with, making it easier to make sure the file is properly 
closed even in the case of exceptions:

def count_lines(filename):
     with open(filename, 'r') as f:
         return sum(1 for line in f)


HTH

-- 
"Honest criticism is hard to take, particularly from a relative, a
friend, an acquaintance, or a stranger."
         -- Franklin P. Jones

Roel Schroeven



More information about the Python-list mailing list