nos
nos

Reputation: 20880

python module with module-wise global variable

I made a python file with several functions in it and I would like to use it as a module. Let's say this file is called mymod.py. The following code is in it.

from nltk.stem.porter import PorterStemmer                      
porter = PorterStemmer()  

def tokenizer_porter(text):                                                                                    
    return [porter.stem(word) for word in text.split()]  

Then I tried to import it in iPython and use tokenizer_porter:

from mymod import * 
tokenizer_porter('this is test')

The following error was generated

TypeError: unbound method stem() must be called with PorterStemmer instance as first argument (got str instance instead)

I don't want to put porter inside the tokenizer_porter function since it feels redundant. What would be the right way to do this? Also, is it possible to avoid

from mymod import * 

in this case?

Many thanks!

Upvotes: 1

Views: 154

Answers (1)

Andrey Ershov
Andrey Ershov

Reputation: 1803

To access global variables in python you need to specify it in fucntion with global keyword

def tokenizer_porter(text):     
    global porter                                                                           
    return [porter.stem(word) for word in text.split()]  

Upvotes: 1

Related Questions