What Is the Python Keyword "With" Used For

What is the python keyword with used for?

In python the with keyword is used when working with unmanaged resources (like file streams). It is similar to the using statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.

From Python Docs:

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with with using.

What is the python with statement designed for?

  1. I believe this has already been answered by other users before me, so I only add it for the sake of completeness: the with statement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers. More details can be found in PEP 343. For instance, the open statement is a context manager in itself, which lets you open a file, keep it open as long as the execution is in the context of the with statement where you used it, and close it as soon as you leave the context, no matter whether you have left it because of an exception or during regular control flow. The with statement can thus be used in ways similar to the RAII pattern in C++: some resource is acquired by the with statement and released when you leave the with context.

  2. Some examples are: opening files using with open(filename) as fp:, acquiring locks using with lock: (where lock is an instance of threading.Lock). You can also construct your own context managers using the contextmanager decorator from contextlib. For instance, I often use this when I have to change the current directory temporarily and then return to where I was:

    from contextlib import contextmanager
    import os

    @contextmanager
    def working_directory(path):
    current_dir = os.getcwd()
    os.chdir(path)
    try:
    yield
    finally:
    os.chdir(current_dir)

    with working_directory("data/stuff"):
    # do something within data/stuff
    # here I am back again in the original working directory

    Here's another example that temporarily redirects sys.stdin, sys.stdout and sys.stderr to some other file handle and restores them later:

    from contextlib import contextmanager
    import sys

    @contextmanager
    def redirected(**kwds):
    stream_names = ["stdin", "stdout", "stderr"]
    old_streams = {}
    try:
    for sname in stream_names:
    stream = kwds.get(sname, None)
    if stream is not None and stream != getattr(sys, sname):
    old_streams[sname] = getattr(sys, sname)
    setattr(sys, sname, stream)
    yield
    finally:
    for sname, stream in old_streams.iteritems():
    setattr(sys, sname, stream)

    with redirected(stdout=open("/tmp/log.txt", "w")):
    # these print statements will go to /tmp/log.txt
    print "Test entry 1"
    print "Test entry 2"
    # back to the normal stdout
    print "Back to normal stdout again"

    And finally, another example that creates a temporary folder and cleans it up when leaving the context:

    from tempfile import mkdtemp
    from shutil import rmtree

    @contextmanager
    def temporary_dir(*args, **kwds):
    name = mkdtemp(*args, **kwds)
    try:
    yield name
    finally:
    shutil.rmtree(name)

    with temporary_dir() as dirname:
    # do whatever you want

What is the keyword license used for in python?

It's not a keyword, it's a constant added by the site module (some others are copyright and credits). If you want to know what it does, try:

print license
>>> Type license() to see the full license text

then if you type

license()

output will be:

A. HISTORY OF THE SOFTWARE


Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
as a successor of a language called ABC. Guido remains Python's
principal author, although it includes many contributions from others.

In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
in Reston, Virginia where he released several versions of the
software.

In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
year, the PythonLabs team moved to Digital Creations (now Zope
Corporation, see http://www.zope.com). In 2001, the Python Software
Foundation (PSF, see http://www.python.org/psf/) was formed, a
non-profit organization created specifically to own Python-related
Intellectual Property. Zope Corporation is a sponsoring member of the
PSF.

All Python releases are Open Source (see http://www.opensource.org for
Hit Return for more, or q (and Return) to quit:

How is the 'is' keyword implemented in Python?

Testing strings with is only works when the strings are interned. Unless you really know what you're doing and explicitly interned the strings you should never use is on strings.

is tests for identity, not equality. That means Python simply compares the memory address a object resides in. is basically answers the question "Do I have two names for the same object?" - overloading that would make no sense.

For example, ("a" * 100) is ("a" * 100) is False. Usually Python writes each string into a different memory location, interning mostly happens for string literals.

When, if ever, to use the 'is' keyword in Python?

You should use is when you want to know whether two objects are the same object. Don't use it when you want to know whether two objects have the same value.

There is a canonical example, but it is unfortunately not very helpful. People will tell you to always test for the None value using x is None instead of x == None. However, there is little practical difference between these cases. (See this question for explanation.)

In some situations, you may wind up creating objects which have the same value but are distinct objects. For instance, you could imagine creating a fantasy wargame in which the player can magically create minions to battle his opponent. So the player might create 100 identical orcs or whatever. Each orc could be represented by an object, and they would be identical in that they have the same properties, but still distinct in that there would be 100 separate objects. Now if the opponent tries to cast a "fireball" spell on one of these orcs, while on the same turn the player tries to cast "protect against fire" on an orc, you might want to check if the target of the fireball spell is the target of the protection spell. Equality wouldn't be enough, because all the orcs are equal, but only one particular orc is the target of each spell, and you want to know if the two targets are the same object. This is a rather contrived example, but should give a broad idea of the kind of situation where you might wind up using is.

What really is a keyword in Python?

Keywords are reserved names, so you can't assign to them.

>>> True = 0
File "<stdin>", line 1
SyntaxError: can't assign to keyword

int is a type; it's perfectly possible to reassign it:

>>> int = str
>>>

(I really wouldn't recommend this, though.)

What does *[, keyword_arg = value] do in Python keyword only function definition?

The Python documentation/help derives from EBNF to describe grammar. A pair of [ ] means "optional" in EBNF and the Python documentation; for terseness, common symbols like ( ) and names are not quoted in the documentation even though this has different meaning in EBNF.

The * and , are derived from Python's call syntax. * means "end of positional parameters".

For the concrete example of

min(iterable, *[, default=obj, key=func]) -> value

this means default and key are optional keyword-only parameters.

How do I use a keyword as a variable name?

As mentioned in the comments, from is a Python keyword so you can't use it as a variable name, or an attribute name. So you need to use an alternative name, and do a conversion when reading or writing the JSON data.

To do the output conversion you can supply a new encoder for json.dumps; you can do that by overriding the ExchangeRates.json method. To do the input conversion, override ExchangeRates.from_json.

The strategy is similar in both cases: we create a copy of the dictionary (so we don't mutate the original), then we create a new key with the desired name and value, then delete the old key.

Here's a quick demo, tested on Python 2.6 and 3.6:

import json

class PropertyEquality(object):
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__)

def __ne__(self, other):
return not self.__eq__(other)

def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, ', '.join(['%s=%s' % (k, v) for (k, v) in self.__dict__.items()]))

class JsonAware(PropertyEquality):
def json(self):
return json.dumps(self, cls=GenericEncoder)

@classmethod
def from_json(cls, json):
return cls(**json)

class ExchangeRatesEncoder(json.JSONEncoder):
def default(self, obj):
d = obj.__dict__.copy()
d['from'] = d['frm']
del d['frm']
return d

class ExchangeRates(JsonAware):
def __init__(self, frm, to, rate):
self.frm = frm
self.to = to
self.rate = rate

def json(self):
return json.dumps(self, cls=ExchangeRatesEncoder)

@classmethod
def from_json(cls, json):
d = json.copy()
d['frm'] = d['from']
del d['from']
return cls(**d)

# Test

a = ExchangeRates('a', 'b', 1.23)
print(a.json())

jdict = {"from": "z", "to": "y", "rate": 4.56, }

b = ExchangeRates.from_json(jdict)
print(b.json())

typical output

{"from": "a", "to": "b", "rate": 1.23}
{"from": "z", "to": "y", "rate": 4.56}

When is del useful in Python?

Firstly, you can del other things besides local variables

del list_item[4]
del dictionary["alpha"]

Both of which should be clearly useful. Secondly, using del on a local variable makes the intent clearer. Compare:

del foo

to

foo = None

I know in the case of del foo that the intent is to remove the variable from scope. It's not clear that foo = None is doing that. If somebody just assigned foo = None I might think it was dead code. But I instantly know what somebody who codes del foo was trying to do.



Related Topics



Leave a reply



Submit