473,660 Members | 2,475 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Context manager for files vs garbage collection

Hi

I was wondering when it was worthwil to use context managers for
file. Consider this example:

def foo():
t = False
for line in file('/tmp/foo'):
if line.startswith ('bar'):
t = True
break
return t

What would the benefit of using a context manager be here, if any?
E.g.:

def foo():
t = False
with file('/tmp/foo') as f:
for line in f:
if line.startswith ('bar'):
t = True
break
return t

Personally I can't really see why the second case would be much
better, I've got used to just relying on the garbage collector... :-)
But what is the use case of a file as a context manager then? Is it
only useful if your file object is large and will stay in scope for a
long time?

Regards
Floris
Jun 27 '08 #1
3 1211
Floris Bruynooghe a écrit :
Hi

I was wondering when it was worthwil to use context managers for
file. Consider this example:

def foo():
t = False
for line in file('/tmp/foo'):
if line.startswith ('bar'):
t = True
break
return t

What would the benefit of using a context manager be here, if any?
E.g.:

def foo():
t = False
with file('/tmp/foo') as f:
for line in f:
if line.startswith ('bar'):
t = True
break
return t

Personally I can't really see why the second case would be much
better, I've got used to just relying on the garbage collector... :-)
IIRC (please someone correct me if I'm wrong), proper release of file
resources as soon as the file object gets out of scope is not garanteed
in the language spec and is implementation dependant.

Jun 27 '08 #2
On Jun 16, 8:24 am, Bruno Desthuilliers <bruno.
42.desthuilli.. .@websiteburo.i nvalidwrote:
>
IIRC (please someone correct me if I'm wrong), proper release of file
resources as soon as the file object gets out of scope is not garanteed
in the language spec and is implementation dependant.
Right. Resources are freed in CPython right after they drop out of
scope. This is not true in other implementations , so it's best to be
explicit.
Jun 27 '08 #3
Floris Bruynooghe <fl************ ***@gmail.com>:
I was wondering when it was worthwil to use context managers for
file. Consider this example:

def foo():
t = False
for line in file('/tmp/foo'):
if line.startswith ('bar'):
t = True
break
return t
Using this code inside a jthon web application might hit the resource limits
of the underlying operating system.

While CPython has a fairly deterministic garbage collector, the JVM gc is
non-deterministic, especially inside the server vm. It keeps objects
around for quite a long time and only frees them, if available memory runs
low or the application is idle. Since file objects don't consume much
memory, they might be hanging around for quite some time still claiming
resources, which are a rare thing on many restricted server environments.

Relying on garbage collection on Python means relying on a non-portable
implementation detail.

--
Freedom is always the freedom of dissenters.
(Rosa Luxemburg)
Jun 27 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
810
by: Ganesh | last post by:
Is there a utility by microsoft (or anyone) to force garbage collection in a process without have access to the process code. regards Ganesh
11
2721
by: Rick | last post by:
Hi, My question is.. if Lisp, a 40 year old language supports garbage collection, why didn't the authors of C++ choose garbage collection for this language? Are there fundamental reasons behind this? Is it because C is generally a 'low level' language and they didn't want garbage collection to creep into C++ and ruin everything? Just wondering :)
3
1697
by: Jerry Sievers | last post by:
Hello. I have session files stored in a special tmp directory specific to a virtual host instance. The Max_lifetime is long 86400 (1 day) which I don't suppose is the problem. Anyway the sessions do indeed expire and "most" of the old session files disappear as expected. Not all however. I am finding several old session files with Unix
34
6405
by: Ville Voipio | last post by:
I would need to make some high-reliability software running on Linux in an embedded system. Performance (or lack of it) is not an issue, reliability is. The piece of software is rather simple, probably a few hundred lines of code in Python. There is a need to interact with network using the socket module, and then probably a need to do something hardware- related which will get its own driver written in C.
5
3593
by: Bob lazarchik | last post by:
Hello: We are considering developing a time critical system in C#. Our tool used in Semiconductor production and we need to be able to take meaurements at precise 10.0 ms intervals( 1000 measurement exactly 10 ms apart. In the future this may decrease to 5ms ). I am concerned that if garbage collection invokes during this time it may interfere with our measurement results. I have looked over the garbage collection mechanism and see no...
8
3034
by: mike2036 | last post by:
For some reason it appears that garbage collection is releasing an object that I'm still using. The object is declared in a module and instantiated within a class that is in turn instantiated by the mainline. The class that instantiated the object in question is definitely still in existence at the point garbage collection swoops in and yanks it out from under my processing. Is there a way to ensure an instantiated object cannot be freed...
12
1373
by: Marcelo Fernandez | last post by:
Hi ! I was wondering if there is tool that could tell me if some of my pointers are still alive when they are suppose to be dead (in case I forget to kill them...). As you have noticed, I am real newbie in c++ programming and I have quite a trouble to remember which pointer should be alive and which one should die (Java garbage collector fault...).
56
3666
by: Johnny E. Jensen | last post by:
Hellow I'am not sure what to think about the Garbage Collector. I have a Class OutlookObject, It have two private variables. Private Microsoft.Office.Interop.Outlook.Application _Application = null; Private Microsoft.Office.Interop.Outlook.NameSpace _Namespace = null; The Constructor: public OutlookObject()
158
7797
by: pushpakulkar | last post by:
Hi all, Is garbage collection possible in C++. It doesn't come as part of language support. Is there any specific reason for the same due to the way the language is designed. Or it is discouraged due to some specific reason. If someone can give inputs on the same, it will be of great help. Regards, Pushpa
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8341
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8751
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8630
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7360
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4176
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.