-2

Hey guys am trying to use the with statement in my code..Since am new to python i just wrote to code to understand the working of with statement..My code

class Employee:
    empCount = 0
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary


c = Employee("blah",1)
c.empCount = ['aad']




class Subin(Employee):

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary


    def __enter__(self):
        return self

    def __exit__(self ,type):
        print 'ok'


    def babe(self):
        with c.empCount as b:
            return 0

b = Subin("sds",1)
b.babe()

When I run the code I get the error:

Traceback (most recent call last):
  File "C:/Python27/dfg", line 38, in <module>
    b.babe()
  File "C:/Python27/dfg", line 33, in babe
    with c.empCount as b:
AttributeError: __exit__

Can you guys tell me why this is happening?

5
  • 4
    That's not what the with keyword does. Read the PEP-343. Please also edit your question and fix the indention of your code. Commented May 8, 2015 at 17:31
  • Please, try to properly format your code. It's totally unreadable as of now. Commented May 8, 2015 at 17:31
  • 1
    Your first problem is that the thing you're trying to use as a context manager with the with statement is not a context manager at all - it's c.empCount, which is a list. Subin on the other hand could (almost) be a context manager, so you'd do something like with Subin("foo",1) as s:. But for that to have any chance of working, you'd need to fix the signature of the __exit__ method first. Commented May 8, 2015 at 17:35
  • @LukasGraf doesn it work with lists or only with classes ?? Commented May 9, 2015 at 13:07
  • @Tichodroma is this only used with classes ..can i use it with lists or functions inside the employee class ?? Commented May 9, 2015 at 13:28

1 Answer 1

3

Firstly, Python code is not "free form". If your indentation is incorrect, it will not compile or run. Cutting and pasting your code into an interpreter will show you that.

Secondly, you're using the with statement wrongly. It's not the Subin class that should work as a context manager (with __enter__ and __exit__ methods although the latter has the wrong number of arguments) but the c.empCount object which is a list here and therefore won't work.

The with statement is described here in the official documentation some examples are provided.

I'd recommend that you play with basic python a little more before trying out context managers.

Sign up to request clarification or add additional context in comments.

4 Comments

doesnt it work with lists ??
A list is not a context manager.
what about the functions inside a class ??..is it a context manager ??
A function (inside or outside a class) is not a context manager.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.