FedoraForum.org - Fedora Support Forums and Community
Results 1 to 2 of 2
  1. #1
    Join Date
    Jan 2011
    Posts
    132

    Python with statement

    http://python.about.com/od/gettingst...t/py25WITH.htm

    On that page there is the following code:
    Code:
    with open(sys.argv[1], "r") as fileIN: 
        for line in fileIN: 
            [some bit of analysis here]
    And if I put print line in the last line it works so I assume that the first line sets fileIN to the contents of sys.argv[1].

    So in theory shoudln't this code set the variable test to tst
    Code:
    with "tst" as test:
        print test
    and therefore print tst? But when I run it I get:
    Code:
    Traceback (most recent call last):
      File "p.py", line 1, in <module>
        with "tst" as test:
    AttributeError: __exit__
    I♥SymLinks
    Fedora 16 64 Bit (Fedora 13 install upgraded to 14 with preupgrade, then 15 using --distro-sync) - KDE 4.6.5 HDD Reporting SMART erorrs, using SSD with Fedora 20, XFCE install with yum install @kde-desktop
    http://forums.fedoraforum.org/showthread.php?p=1524332#post1524332 HELP

  2. #2
    Join Date
    Apr 2007
    Posts
    43

    Re: Python with statement

    That is an interesting theory, and I certainly follow your logic, but it appears that that is not (exactly) the way it works.

    The expression, "tst" is supposed to resolve to a context guard/manager. Apparently "tst" does not meet those requirements, and is why you get an AttributeError, because a context guard would have an __exit__() (as well as an __enter__()).

    After a little googling:
    http://effbot.org/pyref/with.htm

    And the relevant PEP:
    http://www.python.org/dev/peps/pep-0343/

Similar Threads

  1. Switch statement
    By teishu in forum Programming & Packaging
    Replies: 3
    Last Post: 12th February 2007, 03:47 PM
  2. Insert Statement from mySQL
    By AndreasMet in forum Using Fedora
    Replies: 1
    Last Post: 26th November 2006, 11:39 AM
  3. if statement in bash
    By Adesso in forum Programming & Packaging
    Replies: 1
    Last Post: 1st September 2006, 03:33 PM
  4. bash if statement going bunk
    By jim in forum Programming & Packaging
    Replies: 9
    Last Post: 27th January 2006, 04:55 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •