metaprogramming - How to check if a function is pure in Python? -


a pure function function similar mathematical function, there no interaction "real world" nor side-effects. more practical point of view, means pure function can not:

  • print or otherwise show message
  • be random
  • depend on system time
  • change global variables
  • and others

all limitations make easier reason pure functions non-pure ones. majority of functions should pure program can have less bugs.

in languages huge type-system haskell reader can know right start if function or not pure, making successive reading easier.

in python information may emulated @pure decorator put on top of function. decorator validation work. problem lies in implementation of such decorator.

right source code of function buzzwords such global or random or print , complains if finds 1 of them.

import inspect  def pure(function):     source = inspect.getsource(function)     non_pure_indicator in ('random', 'time', 'input', 'print', 'global'):         if non_pure_indicator in source:             raise valueerror("the function {} not pure uses `{}`".format(                 function.__name__, non_pure_indicator))     return function 

however feels weird hack, may or may not work depending on luck, please me in writing better decorator?

i kind of see coming don't think can work. let's take simple example:

def add(a,b):     return + b 

so looks "pure" you. in python + here arbitrary function can anything, depending on bindings in force when called. a + b can have arbitrary side effects.

but it's worse that. if doing standard integer + there's more 'impure' stuff going on.

the + creating new object. if sure caller has reference new object there sense in can think of pure function. can't sure that, during creation process of object, no reference leaked out.

for example:

class registerednumber(int):      numbers = []      def __new__(cls,*args,**kwargs):         self = int.__new__(cls,*args,**kwargs)         self.numbers.append(self)         return self      def __add__(self,other):         return registerednumber(super().__add__(other))  c = registerednumber(1) + 2  print(registerednumber.numbers) 

this show supposedly pure add function has changed state of registerednumber class. not stupidly contrived example: in production code base have classes track each created instance, example, allow access via key.

the notion of purity doesn't make sense in python.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -