Python Package Building - importing function for use in class definition -


i'm working on building python package wrapper around request package , designed make variety of api calls set of databases easier.

currently, package has following directory structure:

package\   - __init__.py   - corefunc.py   subpackage\     - __init__.py     - mod1.py     - mod2.py 

the primary functionality of package lies in mod1.py , mod2.py. mod1.py looks this:

import requests _requests package.corefunc import __func1  class datapull:     def __init__(self, arg1):       self._url = "http://www.somesite.com/info?"       self._api_param = {'argument':__func1(arg1)}       self._pull = _requests.get(self._url, params = self._api_param)     def datatableone(self):         _headers = self._pull.json()['resultsets'][0]['headers']         _values = self._pull.json()['resultsets'][0]['rowset']         return [dict(zip(_headers, value)) value in _values]     def datatabletwo(self):         _headers = self._pull.json()['resultsets'][1]['headers']         _values = self._pull.json()['resultsets'][1]['rowset']         return [dict(zip(_headers, value)) value in _values] 

within corefunc.py, have few functions need use within specific classes in mod1.py , mod2.py. in fact, in third line of class definition, i'm using function (__func1) defined in corefunc modify user input argument ensure correct value passed api call.

corefunc.py looks this:

def __func1(x):     if str(x) == "1999":     return "1999-00" elif len(str(x)) == 4:     try:         return "-".join([str(x),str(int(x) % 100 + 1)])     except:          raise exception("enter four-digit year") else: raise exception("enter four-digit year") 

i'm using class call because call results in more 1 data table , using methods access each of data tables.

my issue when try , create object of class datapull:

newobj = datapull(argument) 

gives me following error:

--------------------------------------------------------------------------- nameerror                                 traceback (most recent call last) <ipython-input-24-e3399cf393bd> in <module>() ----> 1 traceback.extract_stack(package.mode1.datapull("203112"))  c:\users\bradley\anaconda3\lib\site-packages\test-package-py3.4.egg\package\subpackage\mod1.py in __init__(self, arg1)     140         self._url = "http://www.somesite.com/info?" --> 141         self._api_param = {"season":__func1(arg1)}  nameerror: name '_datapull__func1' not defined 

how import __func1 mod1.py fix error?

this case of name mangling, __ in front of within class definition changed _classname__attr. quoting docs:

any identifier of form __spam (at least 2 leading underscores, @ 1 trailing underscore) textually replaced _classname__spam, classname current class name leading underscore(s) stripped. mangling done without regard syntactic position of identifier, long occurs within definition of class.

this done @ source code level, can change name of function going used inside class definition else , work fine.


related cpython code compile.c:

pyobject * _py_mangle(pyobject *privateobj, pyobject *ident) {     /* name mangling: __private becomes _classname__private.        independent how name used. */     const char *p, *name = pystring_asstring(ident);     char *buffer;     size_t nlen, plen;     if (privateobj == null || !pystring_check(privateobj) ||         name == null || name[0] != '_' || name[1] != '_') {         py_incref(ident);         return ident;     }     p = pystring_asstring(privateobj);     nlen = strlen(name);     /* don't mangle __id__ or names dots.         time name dot can occur when        compiling import statement has        package name.         todo(jhylton): decide whether want support        mangling of module name, e.g. __m.x.     */     if ((name[nlen-1] == '_' && name[nlen-2] == '_')         || strchr(name, '.')) {         py_incref(ident);         return ident; /* don't mangle __whatever__ */     }     /* strip leading underscores class name */     while (*p == '_')         p++;     if (*p == '\0') {         py_incref(ident);         return ident; /* don't mangle if class underscores */     }     plen = strlen(p);      if (plen + nlen >= py_ssize_t_max - 1) {         pyerr_setstring(pyexc_overflowerror,                         "private identifier large mangled");         return null;     }      ident = pystring_fromstringandsize(null, 1 + nlen + plen);     if (!ident)         return 0;     /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */     buffer = pystring_as_string(ident);     buffer[0] = '_';     strncpy(buffer+1, p, plen);     strcpy(buffer+1+plen, name);     return ident; } 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -