Python WTF: åãã¢ã¸ã¥ã¼ã«ãäºã¤ï¼
ãµã¼ãã¤ã³ãã¼ã
import foo
éããã¹ã§ã¤ã³ãã¼ã
ããã§ãåãã¢ã¸ã¥ã¼ã«ãï¼åã¤ã³ãã¼ããããªã!ãã¨å±ããã¦ã»ããã
import sys,os
sys.path.insert(0, '..')
import adir.foo
ã¢ã¸ã¥ã¼ã«ã¹ã³ã¼ãã®å¤æ°ã¯éã£ãã¤ã³ã¹ã¿ã³ã¹ãããã«ã±ããåã¾ããã
print foo.module_scope_var
print adir.foo.module_scope_var
確ãã«éã
print adir.foo.module_scope_var==foo.module_scope_var
False
ããã¯ã¢ã¸ã¥ã¼ã«èªä½ãéãããã
print adir.foo==foo
False
ã¢ã¸ã¥ã¼ã«ãããªã³ããã¦ã¿ãã¨
print adir.foo
print foo
ãã¯ãéãã
ãã¡ã¤ã«ã¯ï¼
print foo.__file__
print adir.foo.__file__
/home/tengu/python/wtf/adir/foo.pyc
../adir/foo.pyc
åããã¡ã¤ã«ãªã®ã«â¦
print os.path.abspath(foo.__file__)==os.path.abspath(adir.foo.__file__)
True
ã¤ã¾ã
pythonã¯åããã¡ã¤ã«ãéããã¹ã§ã¤ã³ãã¼ãããã¨è¤æ°ã®ã¢ã¸ã¥ã¼ã«ã使ããã¨ã«ãªãã ã¢ã¸ã¥ã¼ã«ãã¡ã¤ã«ãåä¸ã§ããã®ã¬ãã«ã§çµ±ä¸ãã¦ãããªãã ã¢ã¸ã¥ã¼ã«ã¯ã¤ã³ãã¼ããã¼ã æ¯ã«ç®¡çãããã ä»ã®è¨èªã ã¨ããããå ´åãéè¤ã¤ã³ãã¼ãã¨ãã¦å±ãããæ°ãããã
ãåãã¢ã¸ã¥ã¼ã«ãéãååã§ã¤ã³ãã¼ããã奴ãããã!ãã¨æããããããªããã©ã ãã¬ã¼ã ã¯ã¼ã¯çãªã³ã¼ãã大ããªããã¸ã§ã¯ãã§ä½¿ã£ã¦ããã¨ãç¥ããã¨ãããªããã¨ãããã ä¾ãã°ãdjangoããã¸ã§ã¯ãä¸ã«ä¾¿å©ãªæ±ç¨ã¢ã¸ã¥ã¼ã«ããã£ãã¨ããï¼
- blog/util.py
ãããviewsãåãdirectoryãªãã§ãã®ããã«ã¤ã³ãã¼ã
- blog/views.py: import util
å¥ã®appããã¯ãã®ããã«ã¤ã³ãã¼ã
- link/views.py: import blog.util
utilã«å ±æãããå¤æ°ããã£ããwtfã«ãªã£ã¦ãã¾ãã
ã¤ã¾ããã¤ã³ãã¼ãã®ä»æ¹ã¯ç»ä¸ã«ãã£ãæ¹ãããã£ã¦ãã¨ããªã
éè¤ã¤ã³ãã¼ãçºè¦æ¹
ãããã¯ãã®ããã«ãã§ãã¯ãããã
path_modules={}
for m in sys.modules.values():
if hasattr(m,'__file__'):
path_modules.setdefault(os.path.abspath(m.__file__),[]).append(m)
for path, modules in path_modules.items():
if len(modules)>1:
print 'dup:', path
for m in modules:
print m
dup: /home/tengu/python/wtf/adir/foo.pyc
dup: /usr/lib/python2.6/posixpath.pyc
ãããposixpathããï¼
ããã¯å¥åãåãã¢ã¸ã¥ã¼ã«ã«è§£æ±ºãã¦ãããªã
import os
import posixpath
>>> posixpath
>>> os.path
>>> posixpath==os.path
True