def local_import_aux(name, reload_force=False, app='welcome'): """ In apps, instead of importing a local module (in applications/app/modules) with:: import a.b.c as d you should do:: d = local_import('a.b.c') or (to force a reload): d = local_import('a.b.c', reload=True) This prevents conflict between applications and un-necessary execs. It can be used to import any module, including regular Python modules. """ items = name.replace('/', '.') name = "applications.%s.modules.%s" % (app, items) module = __import__(name) for item in name.split(".")[1:]: module = getattr(module, item) if reload_force: reload(module) return module
def _reload_check(self, name, globals, locals, level): """ Update the date associated to the module and reload the module if the file changed. """ module = sys.modules.get(name) file = self._get_module_file(module) if file: date = self._import_dates.get(file) new_date = None reload_mod = False mod_to_pack = False # Module turning into a package? (special case) try: new_date = os.path.getmtime(file) except: self._import_dates.pop(file, None) # Clean up # Handle module changing in package and # package changing in module: if file.endswith(".py"): # Get path without file ext: file = os.path.splitext(file)[0] reload_mod = os.path.isdir(file) \ and os.path.isfile(file + self.PACKAGE_PATH_SUFFIX) mod_to_pack = reload_mod else: # Package turning into module? file += ".py" reload_mod = os.path.isfile(file) if reload_mod: new_date = os.path.getmtime(file) # Refresh file date if reload_mod or not date or new_date > date: self._import_dates[file] = new_date if reload_mod or (date and new_date > date): if mod_to_pack: # Module turning into a package: mod_name = module.__name__ del sys.modules[mod_name] # Delete the module # Reload the module: NATIVE_IMPORTER(mod_name, globals, locals, [], level) else: reload(module)
def doctests(): u""" doctests: >>> test_unicode=u'ПРоба Є PRobe' >>> test_unicode_word=u'ПРоба' >>> test_number_str='12345' >>> test_unicode u'\\u041f\\u0420\\u043e\\u0431\\u0430 \\u0404 PRobe' >>> print test_unicode ПРоба Є PRobe >>> test_word=test_unicode_word.encode('utf-8') >>> test_str=test_unicode.encode('utf-8') >>> s=Utf8(test_str) >>> s 'ПРоба Є PRobe' >>> type(s) <class '__main__.Utf8'> >>> s == test_str True >>> len(test_str) # wrong length of utf8-string! 19 >>> len(test_unicode) # RIGHT! 13 >>> len(s) # RIGHT! 13 >>> size(test_str) # size of utf-8 string (in bytes) == len(str) 19 >>> size(test_unicode) # size of unicode string in bytes (packed to utf-8 string) 19 >>> size(s) # size of utf-8 string in bytes 19 >>> try: # utf-8 is a multibyte string. Convert it to unicode for use with builtin ord() ... __builtin__.ord('б') # ascii string ... except Exception, e: ... print 'Exception:', e Exception: ord() expected a character, but string of length 2 found >>> ord('б') # utf8.ord() is used(!!!) 1073 >>> ord(u'б') # utf8.ord() is used(!!!) 1073 >>> ord(s[3]) # utf8.ord() is used(!!!) 1073 >>> chr(ord(s[3])) # utf8.chr() and utf8.chr() is used(!!!) 'б' >>> type(chr(1073)) # utf8.chr() is used(!!!) <class '__main__.Utf8'> >>> s=Utf8(test_unicode) >>> s 'ПРоба Є PRobe' >>> s == test_str True >>> test_str == s True >>> s == test_unicode True >>> test_unicode == s True >>> print test_str.upper() # only ASCII characters uppered ПРоба Є PROBE >>> print test_unicode.upper() # unicode gives right result ПРОБА Є PROBE >>> s.upper() # utf8 class use unicode.upper() 'ПРОБА Є PROBE' >>> type(s.upper()) <class '__main__.Utf8'> >>> s.lower() 'проба є probe' >>> type(s.lower()) <class '__main__.Utf8'> >>> s.capitalize() 'Проба є probe' >>> type(s.capitalize()) <class '__main__.Utf8'> >>> len(s) 13 >>> len(test_unicode) 13 >>> s+'. Probe is проба' 'ПРоба Є PRobe. Probe is проба' >>> type(s+'. Probe is проба') <class '__main__.Utf8'> >>> s+u'. Probe is проба' 'ПРоба Є PRobe. Probe is проба' >>> type(s+u'. Probe is проба') <class '__main__.Utf8'> >>> s+s 'ПРоба Є PRobeПРоба Є PRobe' >>> type(s+s) <class '__main__.Utf8'> >>> a=s >>> a+=s >>> a+=test_unicode >>> a+=test_str >>> a 'ПРоба Є PRobeПРоба Є PRobeПРоба Є PRobeПРоба Є PRobe' >>> type(a) <class '__main__.Utf8'> >>> s*3 'ПРоба Є PRobeПРоба Є PRobeПРоба Є PRobe' >>> type(s*3) <class '__main__.Utf8'> >>> a=Utf8("-проба-") >>> a*=10 >>> a '-проба--проба--проба--проба--проба--проба--проба--проба--проба--проба-' >>> type(a) <class '__main__.Utf8'> >>> print "'"+test_str.center(17)+"'" # WRONG RESULT! 'ПРоба Є PRobe' >>> s.center(17) # RIGHT! ' ПРоба Є PRobe ' >>> type(s.center(17)) <class '__main__.Utf8'> >>> (test_word+test_number_str).isalnum() # WRONG RESULT! non ASCII chars are detected as non alpha False >>> Utf8(test_word+test_number_str).isalnum() True >>> s.isalnum() False >>> test_word.isalpha() # WRONG RESULT! Non ASCII characters are detected as non alpha False >>> Utf8(test_word).isalpha() # RIGHT! True >>> s.lower().islower() True >>> s.upper().isupper() True >>> print test_str.zfill(17) # WRONG RESULT! ПРоба Є PRobe >>> s.zfill(17) # RIGHT! '0000ПРоба Є PRobe' >>> type(s.zfill(17)) <class '__main__.Utf8'> >>> s.istitle() False >>> s.title().istitle() True >>> Utf8('1234').isdigit() True >>> Utf8(' \t').isspace() True >>> s.join('•|•') '•ПРоба Є PRobe|ПРоба Є PRobe•' >>> s.join((str('(utf8 тест1)'), unicode('(unicode тест2)','utf-8'), '(ascii test3)')) '(utf8 тест1)ПРоба Є PRobe(unicode тест2)ПРоба Є PRobe(ascii test3)' >>> type(s) <class '__main__.Utf8'> >>> s==test_str True >>> s==test_unicode True >>> s.swapcase() 'прОБА є prOBE' >>> type(s.swapcase()) <class '__main__.Utf8'> >>> truncate(s, 10) 'ПРоба Є...' >>> truncate(s, 20) 'ПРоба Є PRobe' >>> truncate(s, 10, '•••') # utf-8 string as *dots* 'ПРоба Є•••' >>> truncate(s, 10, u'®') # you can use unicode string as *dots* 'ПРоба Є P®' >>> type(truncate(s, 10)) <class '__main__.Utf8'> >>> Utf8(s.encode('koi8-u'), 'koi8-u') 'ПРоба Є PRobe' >>> s.decode() # convert utf-8 string to unicode u'\\u041f\\u0420\\u043e\\u0431\\u0430 \\u0404 PRobe' >>> a='про\\tba' >>> str_tmp=a.expandtabs() >>> utf8_tmp=Utf8(a).expandtabs() >>> utf8_tmp.replace(' ','.') # RIGHT! (default tabsize is 8) 'про.....ba' >>> utf8_tmp.index('b') 8 >>> print "'"+str_tmp.replace(' ','.')+"'" # WRONG STRING LENGTH! 'про..ba' >>> str_tmp.index('b') # WRONG index of 'b' character 8 >>> print "'"+a.expandtabs(4).replace(' ','.')+"'" # WRONG RESULT! 'про..ba' >>> Utf8(a).expandtabs(4).replace(' ','.') # RIGHT! 'про.ba' >>> s.find('Є') 6 >>> s.find(u'Є') 6 >>> s.find(' ', 6) 7 >>> s.rfind(' ') 7 >>> s.partition('Є') ('ПРоба ', 'Є', ' PRobe') >>> s.partition(u'Є') ('ПРоба ', 'Є', ' PRobe') >>> (a,b,c) = s.partition('Є') >>> type(a), type(b), type(c) (<class '__main__.Utf8'>, <class '__main__.Utf8'>, <class '__main__.Utf8'>) >>> s.partition(' ') ('ПРоба', ' ', 'Є PRobe') >>> s.rpartition(' ') ('ПРоба Є', ' ', 'PRobe') >>> s.index('Є') 6 >>> s.rindex(u'Є') 6 >>> s.index(' ') 5 >>> s.rindex(' ') 7 >>> a=Utf8('а б ц д е а б ц д е а\\tб ц д е') >>> a.split() ['а', 'б', 'ц', 'д', 'е', 'а', 'б', 'ц', 'д', 'е', 'а', 'б', 'ц', 'д', 'е'] >>> a.rsplit() ['а', 'б', 'ц', 'д', 'е', 'а', 'б', 'ц', 'д', 'е', 'а', 'б', 'ц', 'д', 'е'] >>> a.expandtabs().split('б') ['а ', ' ц д е а ', ' ц д е а ', ' ц д е'] >>> a.expandtabs().rsplit('б') ['а ', ' ц д е а ', ' ц д е а ', ' ц д е'] >>> a.expandtabs().split(u'б', 1) ['а ', ' ц д е а б ц д е а б ц д е'] >>> a.expandtabs().rsplit(u'б', 1) ['а б ц д е а б ц д е а ', ' ц д е'] >>> a=Utf8("рядок1\\nрядок2\\nрядок3") >>> a.splitlines() ['рядок1', 'рядок2', 'рядок3'] >>> a.splitlines(True) ['рядок1\\n', 'рядок2\\n', 'рядок3'] >>> s[6] 'Є' >>> s[0] 'П' >>> s[-1] 'e' >>> s[:10] 'ПРоба Є PR' >>> s[2:-2:2] 'оаЄPo' >>> s[::-1] 'eboRP Є абоРП' >>> s.startswith('ПР') True >>> s.startswith(('ПР', u'об'),0) True >>> s.startswith(u'об', 2, 4) True >>> s.endswith('be') True >>> s.endswith(('be', 'PR', u'Є')) True >>> s.endswith('PR', 8, 10) True >>> s.endswith('Є', -7, -6) True >>> s.count(' ') 2 >>> s.count(' ',6) 1 >>> s.count(u'Є') 1 >>> s.count('Є', 0, 5) 0 >>> Utf8("Parameters: '%(проба)s', %(probe)04d, %(проба2)s") % { u"проба": s, ... "not used": "???", "probe": 2, "проба2": u"ПРоба Probe" } "Parameters: 'ПРоба Є PRobe', 0002, ПРоба Probe" >>> a=Utf8(u"Параметр: (%s)-(%s)-[%s]") >>> a%=(s, s[::-1], 1000) >>> a 'Параметр: (ПРоба Є PRobe)-(eboRP Є абоРП)-[1000]' >>> if hasattr(Utf8, 'format'): ... Utf8("Проба <{0}>, {1}, {param1}, {param2}").format(s, u"中文字", ... param1="барабан", param2=1000) == 'Проба <ПРоба Є PRobe>, 中文字, барабан, 1000' ... else: # format() method is not used in python with version <2.6: ... print True True >>> u'Б'<u'Ї' # WRONG ORDER! False >>> 'Б'<'Ї' # WRONG ORDER! False >>> Utf8('Б')<'Ї' # RIGHT! True >>> u'д'>u'ґ' # WRONG ORDER! False >>> Utf8('д')>Utf8('ґ') # RIGHT! True >>> u'є'<=u'ж' # WRONG ORDER! False >>> Utf8('є')<=u'ж' # RIGHT! True >>> Utf8('є')<=u'є' True >>> u'Ї'>=u'И' # WRONG ORDER! False >>> Utf8(u'Ї') >= u'И' # RIGHT True >>> Utf8('Є') >= 'Є' True >>> a="яжертиуіопшщїасдфгґхйклчєзьцвбнмюЯЖЕРТИУІОПШЩЇАСДФГҐХЙКЛЧЗЬЦВБНМЮЄ" # str type >>> b=u"яжертиуіопшщїасдфгґхйклчєзьцвбнмюЯЖЕРТИУІОПШЩЇАСДФГҐХЙКЛЧЗЬЦВБНМЮЄ" # unicode type >>> c=Utf8("яжертиуіопшщїасдфгґхйклчєзьцвбнмюЯЖЕРТИУІОПШЩЇАСДФГҐХЙКЛЧЗЬЦВБНМЮЄ") # utf8 class >>> result = "".join(sorted(a)) >>> result[0:20] # result is not utf8 string, because bytes, not utf8-characters were sorted '\\x80\\x81\\x82\\x83\\x84\\x84\\x85\\x86\\x86\\x87\\x87\\x88\\x89\\x8c\\x8e\\x8f\\x90\\x90\\x91\\x91' >>> try: ... unicode(result, 'utf-8') # try to convert result (utf-8?) to unicode ... except Exception, e: ... print 'Exception:', e Exception: 'utf8' codec can't decode byte 0x80 in position 0: unexpected code byte >>> try: # FAILED! (working with bytes, not with utf8-charactes) ... "".join( sorted(a, key=sort_key) ) # utf8.sort_key may be used with utf8 or unicode strings only! ... except Exception, e: ... print 'Exception:', e Exception: 'utf8' codec can't decode byte 0xd1 in position 0: unexpected end of data >>> print "".join( sorted(Utf8(a))) # converting *a* to unicode or utf8-string gives us correct result аАбБвВгГґҐдДеЕєЄжЖзЗиИіІїЇйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩьЬюЮяЯ >>> print u"".join( sorted(b) ) # WRONG ORDER! Default sort key is used ЄІЇАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЮЯабвгдежзийклмнопрстуфхцчшщьюяєіїҐґ >>> print u"".join( sorted(b, key=sort_key) ) # RIGHT ORDER! utf8.sort_key is used аАбБвВгГґҐдДеЕєЄжЖзЗиИіІїЇйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩьЬюЮяЯ >>> print "".join( sorted(c) ) # RIGHT ORDER! Utf8 "rich comparison" methods are used аАбБвВгГґҐдДеЕєЄжЖзЗиИіІїЇйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩьЬюЮяЯ >>> print "".join( sorted(c, key=sort_key) ) # RIGHT ORDER! utf8.sort_key is used аАбБвВгГґҐдДеЕєЄжЖзЗиИіІїЇйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩьЬюЮяЯ >>> Utf8().join(sorted(c.decode(), key=sort_key)) # convert to unicode for better performance 'аАбБвВгГґҐдДеЕєЄжЖзЗиИіІїЇйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩьЬюЮяЯ' >>> for result in sorted(["Іа", "Астро", u"гала", Utf8("Гоша"), "Єва", "шовк", "аякс", "Їжа", ... "ґанок", Utf8("Дар'я"), "білінг", "веб", u"Жужа", "проба", u"тест", ... "абетка", "яблуко", "Юляся", "Київ", "лимонад", "ложка", "Матриця", ... ], key=sort_key): ... print result.ljust(20), type(result) абетка <type 'str'> Астро <type 'str'> аякс <type 'str'> білінг <type 'str'> веб <type 'str'> гала <type 'unicode'> ґанок <type 'str'> Гоша <class '__main__.Utf8'> Дар'я <class '__main__.Utf8'> Єва <type 'str'> Жужа <type 'unicode'> Іа <type 'str'> Їжа <type 'str'> Київ <type 'str'> лимонад <type 'str'> ложка <type 'str'> Матриця <type 'str'> проба <type 'str'> тест <type 'unicode'> шовк <type 'str'> Юляся <type 'str'> яблуко <type 'str'> >>> a=Utf8("中文字") >>> L=list(a) >>> L ['中', '文', '字'] >>> a="".join(L) >>> print a 中文字 >>> type(a) <type 'str'> >>> a="中文字" # standard str type >>> L=list(a) >>> L ['\\xe4', '\\xb8', '\\xad', '\\xe6', '\\x96', '\\x87', '\\xe5', '\\xad', '\\x97'] >>> from string import maketrans >>> str_tab=maketrans('PRobe','12345') >>> unicode_tab={ord(u'П'):ord(u'Ж'), ... ord(u'Р') : u'Ш', ... ord(Utf8('о')) : None, # utf8.ord() is used ... ord('б') : None, # -//-//- ... ord(u'а') : u"中文字", ... ord(u'Є') : Utf8('•').decode(), # only unicode type is supported ... } >>> s.translate(unicode_tab).translate(str_tab, deletechars=' ') 'ЖШ中文字•12345' """ import sys reload(sys) sys.setdefaultencoding("UTF-8") import doctest print("DOCTESTS STARTED...") doctest.testmod() print("DOCTESTS FINISHED")