-4

I have an issue with an object I created and then use in a function.

class environnement:
    def __init__(self, n, dic={}, listr=[], listf=[]):
        self.taille=n
        self.reg=dict(dic)
        self.raccess=listr
        self.faccess=listf

First I create an environment in my function compilProgram and then I use compilInstruction with this environnement:

def compilProgram(fichierSortie, nbrRegDispo, AST):
    DICOFUN={}
    for elt in AST.children:
        if elt.type=='fonctionDef':
            DICOFUN[elt.leaf]=elt.children
            continue
        else :
            pass
    env=environnement(nbrRegDispo)
    print(type(env))
    compteurLabel=0
    for elt in AST.children:
        if elt.type!='fonctionDef':
            (env, compteurLabel)=compilInstruction(env, fichierSortie, elt, compteurLabel)

The print on compilProgram is to check what is env before I give it to compilInstruction (because I have an issue).

def compilInstruction(env, fichierSortie, instruction,compteurLabel):
    print(type(env))
    envInterne=environnement(env.taille, env.reg, env.raccess, env.faccess)
    ...

I've try many other way to copy env, but the problem seems to not come from it. Here is what I get when I try compilProgram on propers arguments :

<class 'Environnement.environnement'> (this is the print from compilProgram)
<class 'Environnement.environnement'> (this is the print from compilInstruction)
<class 'NoneType'> (this again comes from the print in compilInstruction)
...
AttributeError: 'NoneType' object has no attribute 'taille'

Why does the print in compilInstruction run twice, and why does env disappear between the two runs?

saluce
  • 13,035
  • 3
  • 50
  • 67
  • 3
    Unrelated to you question, but you're bound to run into that issue: [“Least Astonishment” in Python: The Mutable Default Argument](http://stackoverflow.com/q/1132941/395760) –  Jun 26 '12 at 16:15

2 Answers2

3

You have two print statements, which explains the printing twice.

You are overwriting env with the return from your first call to the compilInstruction function. It follows that that function is returning a None value as the first element of the tuple it returns.

Marcin
  • 48,559
  • 18
  • 128
  • 201
1

You are calling compilInstruction more than once:

for elt in AST.children:
    if elt.type!='fonctionDef':
        (env, compteurLabel)=compilInstruction(env, fichierSortie, elt, compteurLabel)

You have more than one elt in AST.children that is not 'fonctionDef' (a typo??), so you are invoking compilInstruction more than once. That's why you get more than one print from it. The return value of compilInstruction is being assigned to env and compteurLabel, so env is overwritten with None.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662