-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?

AntoineLB
  • 442
  • 3
  • 17
  • 4
    That's not what the `with` keyword does. Read the [PEP-343](https://www.python.org/dev/peps/pep-0343/). Please also [edit] your question and fix the indention of your code. –  May 08 '15 at 17:31
  • Please, try to properly format your code. It's totally unreadable as of now. – Andrea Corbellini May 08 '15 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](https://docs.python.org/2/reference/datamodel.html#object.__exit__) first. – Lukas Graf May 08 '15 at 17:35
  • @LukasGraf doesn it work with lists or only with classes ?? – coding babe May 09 '15 at 13:07
  • @Tichodroma is this only used with classes ..can i use it with lists or functions inside the employee class ?? – coding babe May 09 '15 at 13:28

1 Answers1

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.

Noufal Ibrahim
  • 66,768
  • 11
  • 123
  • 160